go设计模式之工厂方法

在上一篇文章中,实现了简单工厂模式,通过创建一个工厂类,在工厂方法中根据不同的产品类型创建对应的产品实例。当添加一个产品时,需要修改工厂中的创建方法,这种模式不利于程序的扩展,在本篇文章中,将对简单工厂模式进行扩展,以求达到添加产品时,不需要调整创建方法。

那么怎么实现呢?还按照上文中的手机例子

手机接口: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接口

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值