新建 OperatorFactory.go
package factory // 实际运行类的接口 type Operator interface { SetLeft(int) SetRight(int) Result() int } // 工厂接口 type OperatorFactory interface { Create() Operator }
新建OperatorBase.go
package factory // 数据 type OperatorBase struct { left, right int } // 赋值 func (o *OperatorBase) SetLeft(left int) { o.left = left } func (o *OperatorBase) SetRight(right int) { o.right = right }
新建PlusOperatorFactory.go
package factory // 操作的抽象 加法工厂 type PlusOperatorFactory struct { } // 操作勒种包含操作数 type PlusOperator struct { *OperatorBase } // 实际运行 func (p *PlusOperator) Result() int { return p.right + p.left } func (PlusOperatorFactory) Create() Operator { return &PlusOperator{&OperatorBase{}} }
新建SubOperatorFactory.go
package factory // 操作的抽象 减法工厂 type SubOperatorFactory struct { } // 操作勒种包含操作数 type SubOperator struct { *OperatorBase } // 实际运行 func (p *SubOperator) Result() int { return p.left - p.right } func (SubOperatorFactory) Create() Operator { return &SubOperator{&OperatorBase{}} }
main.go
package main import ( "fmt" "test/design/factory" ) // A X B // X 代表操作 // A B 代表操作数 // X=+ A+B X=- A-B X=% A%B // left, right func main() { var fac factory.OperatorFactory //fac = PlusOperatorFactory{} fac = factory.SubOperatorFactory{} op := fac.Create() op.SetLeft(20) op.SetRight(10) fmt.Println(op.Result()) }