观察者模式:对象间的一种一对多的依赖关系,以便一个对象的状态发生变化时,所有依赖于它的对象都得到通知并自动刷新;
策略模式:定义一系列算法,并将每一个算法封装起来,而且使它们可以相互替换;
观测者模式
1 | type ( |
策略模式
Strategy behavioral design pattern enables an algorithm’s behavior to be selected at runtime.
策略行为设计模式允许在运行时选择算法的行为。
It defines algorithms, encapsulates them, and uses them interchangeably.
它定义算法,封装它们,并交替使用它们。
Implementation
Implementation of an interchangeable operator object that operates on integers.
用整数操作的可互换运算符对象的实现。
1 | type Operator interface { |
Usage
- Addition Operator 加法
1 | type Addition struct{} |
- Multiplication Operator 乘法
1
2
3
4
5
6
7
8type Multiplication struct{}
func (Multiplication) Apply(lval, rval int) int {
return lval * rval
}
mult := Operation{Multiplication{}}
mult.Operate(3, 5) // 15