Go常用设计模式(中)

简介: Go常用设计模式(中)

继上一篇文章,今天来分享下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 总结

由于都是属于行为型模式,策略模式和模板方法模式在实现的过程中非常的类似,但不同的是模板方法模式更偏向于部分功能的复用,而策略模式更偏向于多种功能的选用。

相关文章
|
17天前
|
设计模式 Go 网络安全
[设计模式 Go实现] 结构型~代理模式
[设计模式 Go实现] 结构型~代理模式
|
17天前
|
设计模式 Go
[设计模式 Go实现] 结构型~享元模式
[设计模式 Go实现] 结构型~享元模式
|
17天前
|
设计模式 Go API
[设计模式 Go实现] 结构型~外观模式
[设计模式 Go实现] 结构型~外观模式
|
17天前
|
设计模式 Go
[设计模式 Go实现] 结构型~组合模式
[设计模式 Go实现] 结构型~组合模式
|
17天前
|
设计模式 Go
[设计模式 Go实现] 结构型~装饰模式
[设计模式 Go实现] 结构型~装饰模式
|
17天前
|
设计模式 Go
[设计模式 Go实现] 结构型~适配器模式
[设计模式 Go实现] 结构型~适配器模式
|
17天前
|
设计模式 Go
[设计模式 Go实现] 行为型~解释器模式
[设计模式 Go实现] 行为型~解释器模式
|
17天前
|
设计模式 Go
[设计模式 Go实现] 行为型~迭代器模式
[设计模式 Go实现] 行为型~迭代器模式
|
17天前
|
设计模式 存储 Go
[设计模式 Go实现] 行为型~备忘录模式
[设计模式 Go实现] 行为型~备忘录模式
|
17天前
|
设计模式 Go
[设计模式 Go实现] 行为型~中介者模式
[设计模式 Go实现] 行为型~中介者模式