乐趣区

关于设计模式:设计模式工厂模式

工程目录

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())
}
退出移动版