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 总结

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


相关文章
|
1月前
|
设计模式 Go
go 设计模式之观察者模式
go 设计模式之观察者模式
|
2月前
|
设计模式 Go
Go语言设计模式:使用Option模式简化类的初始化
在Go语言中,面对构造函数参数过多导致的复杂性问题,可以采用Option模式。Option模式通过函数选项提供灵活的配置,增强了构造函数的可读性和可扩展性。以`Foo`为例,通过定义如`WithName`、`WithAge`、`WithDB`等设置器函数,调用者可以选择性地传递所需参数,避免了记忆参数顺序和类型。这种模式提升了代码的维护性和灵活性,特别是在处理多配置场景时。
62 8
|
4月前
|
设计模式 Go
[设计模式 Go实现] 结构型~享元模式
[设计模式 Go实现] 结构型~享元模式
|
4月前
|
设计模式 Go API
[设计模式 Go实现] 结构型~外观模式
[设计模式 Go实现] 结构型~外观模式
|
4月前
|
设计模式 Go
[设计模式 Go实现] 结构型~组合模式
[设计模式 Go实现] 结构型~组合模式
|
4月前
|
设计模式 Go
[设计模式 Go实现] 行为型~迭代器模式
[设计模式 Go实现] 行为型~迭代器模式
|
4月前
|
设计模式 存储 Go
[设计模式 Go实现] 行为型~备忘录模式
[设计模式 Go实现] 行为型~备忘录模式
|
4月前
|
设计模式 Go
[设计模式 Go实现] 结构型~装饰模式
[设计模式 Go实现] 结构型~装饰模式
|
4月前
|
设计模式 Go
[设计模式 Go实现] 行为型~解释器模式
[设计模式 Go实现] 行为型~解释器模式
|
4月前
|
设计模式 Go 网络安全
[设计模式 Go实现] 结构型~代理模式
[设计模式 Go实现] 结构型~代理模式