简单工厂就是生产整个计算器,而工厂方法只生产计算器的一部分;
原有的简单工厂可以生'+' '-' '*' '/' ;但是如果添加新的部件'%',厂房就
需要扩充、修改很可以会影响原来部件的正常生产,这就违背了开放封闭原则;
而工厂方法则不存在这个问题;我新开一个工厂专门生产'%'就可以了。
网易云课堂:http://m.study.163.com/provider/480000001930416/index.htm?share=2&shareId=480000001930416
package main
import (
"fmt"
)
type Operation interface {
Exe(int, int) int
}
type FactoryAdd struct{}
type OperationAdd struct{}
func (this *FactoryAdd) Create() Operation {
return &OperationAdd{}
}
func (this *OperationAdd) Exe(a int, b int) int {
return a + b
}
type FactorySub struct{}
type OperationSub struct{}
func (this *FactorySub) Create() Operation {
return &OperationSub{}
}
func (this *OperationSub) Exe(a int, b int) int {
return a - b
}
type FactoryMul struct{}
type OperationMul struct{}
func (this *FactoryMul) Create() Operation {
return &OperationMul{}
}
func (this *OperationMul) Exe(a int, b int) int {
return a * b
}
type FactoryDiv struct{}
type OperationDiv struct{}
func (this *FactoryDiv) Create() Operation {
return &OperationDiv{}
}
func (this *OperationDiv) Exe(a int, b int) int {
return a / b
}
// 新增一个"%"操作,不影响原来的代码,符合开放封闭原则
type FactoryMod struct{}
type OperationMod struct{}
func (this *FactoryMod) Create() Operation {
return &OperationMod{}
}
func (this *OperationMod) Exe(a int, b int) int {
return a % b
}
func main() {
fmt.Println(
(&FactoryAdd{}).Create().Exe(10, 5),
(&FactorySub{}).Create().Exe(10, 5),
(&FactoryMul{}).Create().Exe(10, 5),
(&FactoryDiv{}).Create().Exe(10, 5),
(&FactoryMod{}).Create().Exe(10, 5))
}
输出结果:
15 5 50 2 0