定义:在创建一个对象时不向客户暴露内部细节,并提供一个创建对象的通用接口。
类图:简单工厂把实例化的操作单独放到一个类中,这个类就成为简单工厂类,让简单工厂类来决定应该用哪个具体子类来实例化。
这样做能把客户类和具体子类的实现解耦,客户类不再需要知道有哪些子类以及应当实例化哪个子类。客户类往往有多个,如果不使用简单工厂,那么所有的客户类都要知道所有子类的细节。而且一旦子类发生改变,例如增加子类,那么所有的客户类都要进行修改。
案例:一个电脑产品类,被Huawei
、Apple
继承,简单工厂类中对电脑子类进行创建,客户端只需要调用简单工厂类对象创建电脑实例。
//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)
}
}