首页
学习
活动
专区
圈层
工具
发布

go设计模式之抽象工厂

在上一篇文章中,通过手机的例子对工厂方法进行了展开。制造商不单单只生产手机这一种产品,同时也生产pc,如果工厂扩展其它业务,工厂方法模式就不适用了。为了实现工厂扩展其它业务这个需要,通过抽象工厂这种模式实现这个需要。

以下就是实现的代码

代码语言:javascript
复制
package main

import "fmt"

type IProduct interface {
	ShowBrand()
}

type IPhone struct {
}

func (p *IPhone) ShowBrand() {
	fmt.Println("我是苹果手机")
}

type Mac struct {
}

func (pc *Mac) ShowBrand() {
	fmt.Println("我是苹果电脑")
}

type Factory interface {
	CreatePhone() IPhone
	CreatePc() Mac
}


// 苹果工厂
type IFactory struct {
}

func (F *IFactory) CreatePhone() IProduct {
	return &IPhone{}
}

func (F *IFactory) CreatePc() IProduct {
	return &Mac{}
}

func main() {
	var  factory = &IFactory{}

    phone := factory.CreatePhone()
    phone.ShowBrand()

    pc := factory.CreatePc()
    pc.ShowBrand()
}

以上就是抽象工厂模式,抽象一个工厂类,创建各个产品的方法,通过具体的工厂类实现该接口

下一篇
举报
领券