[go設計模式]工廠方法模式
簡單工廠就是生產整個計算器,而工廠方法只生產計算器的一部分;
原有的簡單工廠可以生’+’ ‘-‘ ‘*’ ‘/’ ;但是如果添加新的部件’%’,廠房就
需要擴充、修改很可以會影響原來部件的正常生產,這就違背了開放封閉原則;
而工廠方法則不存在這個問題;我新開一個工廠專門生產’%’就可以了。
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