继上一篇文章,今天来分享下 Go 常用设计模式中的行为型模式——策略模式和模板方法模式。
1 策略模式
1.1 概念
策略模式更像是把接口比做成一种行为集合,由对象去选择性的实现行为集合中的某些行为,而实现具体行为需要由某种策略,策略模式因此而生。
1.2 代码
首先定义行为集接口 Operator,包含具体行为 Apply,具体对象行为集中的行为环境,实现再定义两个对象 Addition、Multiplication 实现具体的行为。
实现具体行为时要在行为环境中指定具体的策略,就是说明要实现哪个行为,然后再调用具体的方法。
代码:
type Operator interface { Apply(int, int) int}
type Operation struct { Operator Operator}
func (o *Operation) Operate(leftValue, rightValue int) int { return o.Operator.Apply(leftValue, rightValue)}
type Addition struct{}
func (Addition) Apply(val1, val2 int) int { return val1 + val2}
type Multiplication struct{}
func (Multiplication) Apply(val1, val2 int) int { return val1 * val2}
复制代码
测试:
func TestStrategy(t *testing.T) { operation := behavioral.Operation{Operator: behavioral.Multiplication{}} i := operation.Operate(3, 5) fmt.Println(i) add := behavioral.Operation{Operator: behavioral.Addition{}} operate := add.Operate(3, 5) fmt.Println(operate)}
复制代码
2 模板方法模式
2.1 概念
在模板模式(Template Pattern)中,一个抽象类公开定义了执行它的方法的方式/模板。它的子类可以按需要重写方法实现,但调用将以抽象类中定义的方式进行。
2.2 代码
type Signature interface { Open() Close()}
type SignatureImpl struct {}
func (p *SignatureImpl) write(name string) { fmt.Printf("Hello %s \n", name)}
func (p *SignatureImpl) Prepare(s Signature, name string) { s.Open() p.write(name) s.Close()}
type PenSignatureImpl struct{}
func (*PenSignatureImpl) Open() { fmt.Println("open Pen")}
func (*PenSignatureImpl) Close() { fmt.Println("close Pen")}
复制代码
测试:
func TestTemplate(t *testing.T) { var impl behavioral.SignatureImpl impl.Prepare(&behavioral.PenSignatureImpl{}, "zs")}
复制代码
3 总结
由于都是属于行为型模式,策略模式和模板方法模式在实现的过程中非常的类似,但不同的是模板方法模式更偏向于部分功能的复用,而策略模式更偏向于多种功能的选用。
评论