go设计模式之工厂方法
工厂方法模式使用子类的方式延迟生成对象到子类中实现. Go中不存在继承, 所以使用匿名组合来实现. 测试代码:
// factorymethod.go
package factorymethod
// Operator 是被封装的实际类接口
type Operator interface {
SetA(int)
SetB(int)
Result() int
}
// OperatorFactory 是工厂接口
type OpertatorFactory interface {
Create() Operator
}
//OperatorBase 是Opertator接口实现的基类, 封装公用方法
type OperatorBase struct {
a, b int
}
// SetA 设置A
func (o *OperatorBase) SetA(a int) {
o.a = a
}
//SetB 设置B
func (o *OperatorBase) SetB(b int) {
o.b = b
}
//PlusOperatorFactory 是 PlusOperator的工厂类
type PlusOperatorFacroty struct{}
func (PlusOperatorFacroty) Create() Operator {
return &PlusOperator{
OperatorBase: &OperatorBase{},
}
}
//PlusOperator Operator的实际加法实现
type PlusOperator struct {
*OperatorBase
}
//Result 获取结果
func (o PlusOperator) Result() int {
return o.a + o.b
}
//MinusOperatorFactory是MinusOperator的工厂类
type MinusOperatorFactory struct{}
func (MinusOperatorFactory) Create() Operator {
return &MinusOperator{
OperatorBase: &OperatorBase{},
}
}
//MinusOperator Operator的实际减法实现
type MinusOperator struct {
*OperatorBase
}
//Result 获取结果
func (o MinusOperator) Result() int {
return o.a - o.b
}
// factorymethod_test.go
package factorymethod
import "testing"
func compute(factory OpertatorFactory, a, b int) int {
op := factory.Create()
op.SetA(a)
op.SetB(b)
return op.Result()
}
func TestOperator(t *testing.T) {
var (
factory OpertatorFactory
)
factory = PlusOperatorFacroty{}
if compute(factory, 1, 2) != 3 {
t.Fatal("error with factory method pattern")
}
factory = MinusOperatorFactory{}
if compute(factory, 4, 2) != 2 {
t.Fatal("error with factory method pattern")
}
}
「真诚赞赏,手留余香」
真诚赞赏,手留余香
使用微信扫描二维码完成支付
