12-抽象工廠方法模式(Easy搞定Golang設計模式)

package main // ---- 抽象層 ---- type GPU interface { Display() } type MemoryBank interface { Storage() } type CPU interface { Calculate() } type AbstractComputerFactory interface { CreateGPU() GPU CreateMemoryBank() MemoryBank CreateCPU() CPU } // ---- 實現(xiàn)層 ---- // Inter type InterGPU struct { } func (t *InterGPU) Display() { println("Inter生產(chǎn)的顯卡:開始display") } type InterMemoryBank struct { } func (t *InterMemoryBank) Storage() { println("Inter生產(chǎn)的內(nèi)存:開始storage") } type InterCPU struct { } func (t *InterCPU) Calculate() { println("Inter生產(chǎn)的CPU:開始calculate") } type InterFactory struct { } func (t *InterFactory) CreateGPU() GPU { return new(InterGPU) } func (t *InterFactory) CreateMemoryBank() MemoryBank { return new(InterMemoryBank) } func (t *InterFactory) CreateCPU() CPU { return new(InterCPU) } // Nvidia type NvidiaGPU struct { } func (t *NvidiaGPU) Display() { println("Nvidia生產(chǎn)的顯卡:開始display") } type NvidiaMemoryBank struct { } func (t *NvidiaMemoryBank) Storage() { println("Nvidia生產(chǎn)的內(nèi)存:開始storage") } type NvidiaCPU struct { } func (t *NvidiaCPU) Calculate() { println("Nvidia生產(chǎn)的CPU:開始calculate") } type NvidiaFactory struct { } func (t *NvidiaFactory) CreateGPU() GPU { return new(NvidiaGPU) } func (t *NvidiaFactory) CreateMemoryBank() MemoryBank { return new(NvidiaMemoryBank) } func (t *NvidiaFactory) CreateCPU() CPU { return new(NvidiaCPU) } // Kingston type KingstonGPU struct { } func (t *KingstonGPU) Display() { println("Kingston生產(chǎn)的顯卡:開始display") } type KingstonMemoryBank struct { } func (t *KingstonMemoryBank) Storage() { println("Kingston生產(chǎn)的內(nèi)存:開始storage") } type KingstonCPU struct { } func (t *KingstonCPU) Calculate() { println("Kingston生產(chǎn)的CPU:開始calculate") } type KingstonFactory struct { } func (t *KingstonFactory) CreateGPU() GPU { return new(KingstonGPU) } func (t *KingstonFactory) CreateMemoryBank() MemoryBank { return new(KingstonMemoryBank) } func (t *KingstonFactory) CreateCPU() CPU { return new(KingstonCPU) } //組裝電腦 type Computer struct { gpu GPU memoryBank MemoryBank cpu CPU } func (c *Computer) ShowComputer() { println("----", "電腦配置", "----") c.gpu.Display() c.memoryBank.Storage() c.cpu.Calculate() println() } func NewComputer(gpu GPU, memoryBank MemoryBank, cpu CPU) *Computer { return &Computer{gpu: gpu, memoryBank: memoryBank, cpu: cpu} } //業(yè)務邏輯層 func main() { interFac := new(InterFactory) nvidiaFac := new(NvidiaFactory) kingstonFac := new(KingstonFactory) //第一臺電腦 NewComputer(interFac.CreateGPU(), interFac.CreateMemoryBank(), interFac.CreateCPU()).ShowComputer() //第二臺電腦 NewComputer(nvidiaFac.CreateGPU(), kingstonFac.CreateMemoryBank(), interFac.CreateCPU()).ShowComputer() }
標簽: