设计模式 - 简单工厂 - go语言实现

定义:在创建一个对象时不向客户暴露内部细节,并提供一个创建对象的通用接口。

类图:简单工厂把实例化的操作单独放到一个类中,这个类就成为简单工厂类,让简单工厂类来决定应该用哪个具体子类来实例化。

这样做能把客户类和具体子类的实现解耦,客户类不再需要知道有哪些子类以及应当实例化哪个子类。客户类往往有多个,如果不使用简单工厂,那么所有的客户类都要知道所有子类的细节。而且一旦子类发生改变,例如增加子类,那么所有的客户类都要进行修改。

在这里插入图片描述

案例:一个电脑产品类,被HuaweiApple继承,简单工厂类中对电脑子类进行创建,客户端只需要调用简单工厂类对象创建电脑实例。

//Client
package main

func main() {
	var simpleFactory = new(SimpleFactory) // 简单工厂类
	var apple Computer = simpleFactory.CreateProduct("Apple")
	var huawei Computer = simpleFactory.CreateProduct("Huawei")
	apple.Brand()
	huawei.Brand()
}
//output
//This Computer Brand is  Apple
//This Computer Brand is  Huawei
//Product
package main

import "fmt"

type Computer interface {   // 产品类,下面是产品类的三个子类
	Brand()
}

type Apple struct {
	Name string
}

func (this *Apple) Brand()  {
	this.Name = "Apple"
	fmt.Println("This Computer Brand is ",this.Name)
}

type Huawei struct {
	Name string
}

func (this *Huawei) Brand()  {
	this.Name = "Huawei"
	fmt.Println("This Computer Brand is ",this.Name)
}

type Other struct {
	Name string
}

func (this *Other) Brand()  {
	this.Name = "Nothing"
	fmt.Println("This Computer Brand is ",this.Name)
}
//SimpleFactory
package main

type SimpleFactory struct {  // 简单工厂类
	
}

func (this *SimpleFactory) CreateProduct(name string) Computer {
	if name == "Apple" {
		return new(Apple)
	} else if name == "Huawei" {
		return new(Huawei)
	} else {
		return new(Other)
	}
}

参考CS-Notes/notes/设计模式.md

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值