GO设计模式04工厂方法模式
Posted XY丶YX
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了GO设计模式04工厂方法模式相关的知识,希望对你有一定的参考价值。
代码:
package main
import (
"fmt"
)
//Operator 是被封装的实际类接口
type Operator interface {
SetA(int)
SetB(int)
Result() int
}
//OperatorBase 是Operator 接口实现的基类,封装公用方法
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
}
//----------------------------------------------------------------------------
//PlusOperator Operator 的实际加法实现
type PlusOperator struct {
*OperatorBase
}
//Result 获取结果
func (o PlusOperator) Result() int {
return o.a + o.b
}
//----------------------------------------------------------------------------
//MinusOperator Operator 的实际减法实现
type MinusOperator struct {
*OperatorBase
}
//Result 获取结果
func (o MinusOperator) Result() int {
return o.a - o.b
}
//----------------------------------------------------------------------------
//OperatorFactory 是工厂接口
type OperatorFactory interface {
Create() Operator
}
//PlusOperatorFactory 是 PlusOperator 的工厂类
type PlusOperatorFactory struct{}
func (p PlusOperatorFactory) Create() Operator {
return &PlusOperator{
OperatorBase: &OperatorBase{},
}
}
//MinusOperatorFactory 是 MinusOperator 的工厂类
type MinusOperatorFactory struct{}
func (m MinusOperatorFactory) Create() Operator {
return &MinusOperator{
OperatorBase: &OperatorBase{},
}
}
//----------------------------------------------------------------------------
func compute(factory OperatorFactory, a, b int) int {
op := factory.Create()
op.SetA(a)
op.SetB(b)
return op.Result()
}
func main() {
fmt.Println("hello")
factory1 := PlusOperatorFactory{}
if compute(factory1, 1, 2) != 3 {
fmt.Println("error with factory method pattern")
}
fmt.Println("success1")
factory2 := MinusOperatorFactory{}
if compute(factory2, 4, 2) != 2 {
fmt.Println("error with factory method pattern")
}
fmt.Println("success2")
}
以上是关于GO设计模式04工厂方法模式的主要内容,如果未能解决你的问题,请参考以下文章