工厂方法模式使用子类的方式延迟生成对象到子类中实现。
    Go中不存在继承 所以使用匿名组合来实现

    1. package main
    2. import "fmt"
    3. type Operator interface {
    4. SetA(int)
    5. SetB(int)
    6. Result() int
    7. }
    8. type OperatorBase struct {
    9. a,b int
    10. }
    11. func (o *OperatorBase)SetA(a int) {
    12. o.a = a
    13. }
    14. func (o *OperatorBase)SetB(b int){
    15. o.b = b
    16. }
    17. type PlusOperator struct {
    18. *OperatorBase
    19. }
    20. func(o PlusOperator)Result()int {
    21. return o.a+o.b
    22. }
    23. type MinusOperator struct {
    24. *OperatorBase
    25. }
    26. func(o MinusOperator)Result()int {
    27. return o.a-o.b
    28. }
    29. type OperatorFactory interface {
    30. Create() Operator
    31. }
    32. type PlusOperatorFactory struct {
    33. }
    34. func(PlusOperatorFactory)Create()Operator{
    35. return &PlusOperator{&OperatorBase{}}
    36. }
    37. type MinusOperatorFactory struct {
    38. }
    39. func(MinusOperatorFactory)Create()Operator{
    40. return &MinusOperator{&OperatorBase{}}
    41. }
    42. func compute(factory OperatorFactory, a, b int) int {
    43. op := factory.Create()
    44. op.SetA(a)
    45. op.SetB(b)
    46. return op.Result()
    47. }
    48. func main() {
    49. fmt.Println(compute(PlusOperatorFactory{},2,1))
    50. fmt.Println(compute(MinusOperatorFactory{},2,1))
    51. }