GO设计模式03简单工厂模式
Posted XY丶YX
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了GO设计模式03简单工厂模式相关的知识,希望对你有一定的参考价值。
(注:本文为http://c.biancheng.net/view/1317.html学习笔记)
代码
package main
import (
"fmt"
)
type Phone interface {
ShowBrand()
}
type IPhone struct {
}
func (phone IPhone) ShowBrand() {
fmt.Println("[Phone Brand]: Apple")
}
type HPhone struct {
}
func (phone HPhone) ShowBrand() {
fmt.Println("[Phone Brand]: Huawei")
}
type XPhone struct {
}
func (phone XPhone) ShowBrand() {
fmt.Println("[Phone Brand]: Xiaomi")
}
type PhoneFactory struct {
}
func (factory PhoneFactory) CreatePhone(brand string) Phone {
switch brand {
case "HW":
return new(HPhone)
case "XM":
return new(XPhone)
case "PG":
return new(IPhone)
default:
return nil
}
}
func main() {
var phone Phone
factory := new(PhoneFactory)
phone = factory.CreatePhone("HW")
phone.ShowBrand()
phone = factory.CreatePhone("XM")
phone.ShowBrand()
phone = factory.CreatePhone("PG")
phone.ShowBrand()
}
以上是关于GO设计模式03简单工厂模式的主要内容,如果未能解决你的问题,请参考以下文章