go設計模式之抽象工廠

在上一篇文章中,通過手機的例子對工廠方法進行了展開。製造商不單單隻生產手機這一種產品,同時也生產pc,如果工廠擴展其它業務,工廠方法模式就不適用了。爲了實現工廠擴展其它業務這個需要,通過抽象工廠這種模式實現這個需要。

以下就是實現的代碼

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()
}

以上就是抽象工廠模式,抽象一個工廠類,創建各個產品的方法,通過具體的工廠類實現該接口

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章