在上一篇文章中,实现了简单工厂模式,通过创建一个工厂类,在工厂方法中根据不同的产品类型创建对应的产品实例。当添加一个产品时,需要修改工厂中的创建方法,这种模式不利于程序的扩展,在本篇文章中,将对简单工厂模式进行扩展,以求达到添加产品时,不需要调整创建方法。
那么怎么实现呢?还按照上文中的手机例子
手机接口:Phone interface
实例:IPhone, XiaoMI, huawei
方法:showBrand()
工厂接口:Factory interface
工厂实例:Factory
创建方法:createPhone
该实现模式通过实现具体产品的工厂类,通过该类的方法实现对应产品类的创建,在客户端调用时,创建该类。
具体实现,看以下的实现demo
package main
import "fmt"
type Phone interface {
ShowBrand()
}
type Factory interface {
CreatePhone() Phone
}
// iphone
type IPhone struct {
}
func (p *IPhone) ShowBrand() {
fmt.Println("我是苹果手机")
}
// 华为
type HPhone struct {
}
func (p *HPhone) ShowBrand() {
fmt.Println("我是华为手机")
}
// 小米
type XPhone struct {
}
func (p *XPhone) ShowBrand() {
fmt.Println("我是小米手机")
}
// 华为工厂
type HFactory struct {
}
func (F *HFactory) CreatePhone() Phone {
return &HPhone{}
}
// 苹果工厂
type IFactory struct {
}
func (F *IFactory) CreatePhone() Phone {
return &IPhone{}
}
// 小米工厂
type XFactory struct {
}
func (F *XFactory) CreatePhone() Phone {
return &XPhone{}
}
func main() {
var phone Phone
// 苹果工厂实例
appleFactory := &IFactory{}
phone = appleFactory.CreatePhone()
phone.ShowBrand()
// 小米手机工厂
xmFactory := &XFactory{}
phone = xmFactory.CreatePhone()
phone.ShowBrand()
// 华为手机
huaweiFactory := &HFactory{}
phone = huaweiFactory.CreatePhone()
phone.ShowBrand()
}
复制代码
通过该种方式,可以自由的实现对产品的扩展。添加新的手机时,实现实现Phone接口,在实现一个创建该产品的方法,需要实现Factory接口