1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| * 简单工厂模式
package main
import ( "fmt" )
type Operater interface { Operate(int, int) int }
type AddOperate struct { }
func (this *AddOperate) Operate(rhs int, lhs int) int { return rhs + lhs }
type MultipleOperate struct { }
func (this *MultipleOperate) Operate(rhs int, lhs int) int { return rhs * lhs }
type OperateFactory struct { }
func NewOperateFactory() *OperateFactory { return &OperateFactory{} }
func (this *OperateFactory) CreateOperate(operatename string) Operater { switch operatename { case "+": return &AddOperate{} case "*": return &MultipleOperate{} default: panic("无效运算符号") return nil } }
func main() { Operator := NewOperateFactory().CreateOperate("+") fmt.Printf("add result is %d\n", Operator.Operate(1, 2)) }
|