共计 1149 个字符,预计需要花费 3 分钟才能阅读完成。
工程目录
OperatorFactory.go
package Factory
// 理论运行类的接口
type Operator interface {SetLeft(int)
SetRight(int)
Result() int}
// 工厂接口
type OperatorFactory interface {Create() Operator
}
OperatorData.go
package Factory
// 数据
type OperatorData struct {left, right int}
// 赋值
func (op *OperatorData) SetLeft(left int) {op.left = left}
func (op *OperatorData) SetRight(right int) {op.right = right}
PlusOpertaorFactory.go
package Factory
// 操作的形象
type PlusOpertaorFactory struct {}
// 操作类中蕴含操作数
type PlusOpertaor struct {*OperatorData}
// 理论运行办法
func(o PlusOpertaor) Result() int {return o.right + o.left}
func(PlusOpertaorFactory) Create() Operator {return &PlusOpertaor{&OperatorData{}}
}
SubOpertaorFactory.go
package Factory
// 操作的形象
type SubOpertaorFactory struct {}
// 操作类中蕴含操作数
type SubOpertaor struct {*OperatorData}
// 理论运行办法
func(o SubOpertaor) Result() int {return o.left - o.right}
func(SubOpertaorFactory) Create() Operator {return &SubOpertaor{&OperatorData{}}
}
factory_test.go
package Factory
import (
"fmt"
"testing"
)
func TestOpertaorFactory(t *testing.T) {
var fac OperatorFactory
fac = PlusOpertaorFactory{}
op := fac.Create()
op.SetLeft(20)
op.SetRight(10)
fmt.Println(op.Result())
fac = SubOpertaorFactory{}
op = fac.Create()
op.SetLeft(30)
op.SetRight(20)
fmt.Println(op.Result())
}
正文完