模式特点:工厂类根据条件产生不同功能的运算类对象,客户端不需要知道具体的运算类。 程序实例:四则运算计算器,根据用户的输入产生相应的运算类,用这个运算类处理具体的运算。
package mainimport ( "fmt")type Operation struct { a float64 b float64}func (this *Operation) Init(a float64, b float64) { this.a = a this.b = b}type Operator interface { GetResult() float64 Init(a float64, b float64)}type Add struct { Operation}func (this *Add) GetResult() float64 { return this.a + this.b}type Sub struct { Operation}func (this *Sub) GetResult() float64 { return this.a - this.b}type Mul struct { Operation}func (this *Mul) GetResult() float64 { return this.a * this.b}type Div struct { Operation}func (this *Div) GetResult() float64 { return this.a / this.b}type OperationFactory struct {}func (this *OperationFactory) CreateOperator(oper byte) (operator Operator) { switch oper { case '+': operator = &Add{} case '-': operator = &Sub{} case '*': operator = &Mul{} case '/': operator = &Div{} default: panic("运算符号错误!") } return}func main() { f := &OperationFactory{} add := f.CreateOperator('+') add.Init(1, 2) fmt.Println(add.GetResult())}