go設計模式之簡單工廠

簡單工廠是設計模式中最簡單的一創建類型模式,通過一個手機的例子,來展示該模式的使用。

先來看下類圖的實現

接口:Phone interface

實例:IPhone, XiaoMI, huawei

方法:showBrand()

實現代碼如下:

package main

import "fmt"

// 手機類型枚舉
type Brand int

const (
	Hawei Brand = 0
	Apple Brand = 1
	XM    Brand = 2
)

type Phone interface {
	ShowBrand()
}

// iphone
type IPhone struct {
}

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

// 華爲
type HPhone struct {
}

func (p *HPhone) ShowBrand() {
	fmt.Println("我是華爲手機")
}

// 小米
type XPhone struct {
}

func (p *XPhone) ShowBrand() {
	fmt.Println("我是華爲手機")
}

func NewPhone(brand Brand) Phone {
	switch brand {
	case Hawei:
		return &HPhone{}
	case Apple:
		return &IPhone{}
	case XM:
		return &XPhone{}
	default:
		return nil
	}
}

func main() {
	var phone Phone

	// 華爲手機
	phone = NewPhone(Hawei)
	phone.ShowBrand()

	// 小米手機
	phone = NewPhone(XM)
	phone.ShowBrand()

	// 蘋果手機
	phone = NewPhone(Apple)
	phone.ShowBrand()
}

此處使用了go語言的枚舉,來定義手機的型號

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