设计模式——抽象工厂

先用一个需求引入工厂模式

在这里插入图片描述
这里我们的需求就是,按照不同的种类,生成不同种类的对象,当然,我们可以设计九个类,对应不同种类的对象,但是如果每次添加新的产品,我们可能就要修改核心代码,这样会引出一个解决方法——抽象工厂

抽象工厂

对于生成这类的对象,他们有共同点还有不同点,不同种类的风格,但是可以生成同一类产品,那么我们可以先声明不同物品要实现的接口,然后每个工厂生产这个对象都要实现这个接口。

我们使用go来实现。

package main

type PublicFunction interface {
	HasLegs() int
}

type IChair interface {
	PublicFunction
	IsSitDown() bool
}

type ITable interface {
	PublicFunction
	IsFull() bool
}

type ISofa interface {
	PublicFunction
	IsFull() bool
}

type Factory interface {
	MakeChair() IChair
	MakeTable() ITable
	MakeSofa() ISofa
}

func GetFactory(brand string) Factory {
	if brand == "modern" {
		return ModernFactory{}
	}
	return ModernFactory{}
}

type Chair struct {
	Part       string
	LegsNumber int
	SitDown    bool
}

func (c Chair) HasLegs() int {
	return c.LegsNumber
}

func (c Chair) IsSitDown() bool {
	return c.SitDown
}

type Table struct {
	Part       string
	LegsNumber int
	Full       bool
}

func (t Table) HasLegs() int {
	return t.LegsNumber
}

func (t Table) IsFull() bool {
	return t.Full
}

type Sofa struct {
	Part       string
	LegsNumber int
	Full       bool
}

func (s Sofa) HasLegs() int {
	return s.LegsNumber
}

func (s Sofa) IsFull() bool {
	return s.Full
}

type ModernFactory struct {
}

func (m ModernFactory) MakeChair() IChair {
	return Chair{SitDown: false, LegsNumber: 4, Part: "modern"}
}

func (m ModernFactory) MakeTable() ITable {
	return Table{LegsNumber: 4, Full: false, Part: "modern"}
}

func (m ModernFactory) MakeSofa() ISofa {
	return Sofa{Full: false, Part: "modern", LegsNumber: 4}
}

func main() {
	factory := GetFactory("modern")
	sofa := factory.MakeSofa()
	fmt.Printf("the sofa is full ? %t ,the sofa has %d legs ", sofa.IsFull(), sofa.HasLegs())
}

适用性:

  • 一个系统要独立于它的产品的创建、组合和表示
  • 要强调一系列相关的产品对象的设计以便进行联合使用

总结:

  1. 根据我们需要的模型,我们需要横向建立接口(Factory接口)纵向建立接口(Chair、Table、Sofa)
  2. 返回的类型一般是接口,一般不会是结构体,通过接口操作结构体。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值