GO设计模式05抽象工厂模式
Posted XY丶YX
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了GO设计模式05抽象工厂模式相关的知识,希望对你有一定的参考价值。
package main
import (
"fmt"
)
//抽象产品
type Pizza interface {
ProducePizza() string
}
type Hamburger interface {
ProduceHamburger() string
}
//具体产品Pizza
type KFCPizza struct{}
type MJPizza struct{}
func (*KFCPizza) ProducePizza() string {
return "Produce: KFC Pizza"
}
func (*MJPizza) ProducePizza() string {
return "Produce: MJ Pizza"
}
//具体产品Hamburger
type KFCHamburger struct{}
type MJHamburger struct{}
func (*KFCHamburger) ProduceHamburger() string {
return "Produce: KFC Hamburger"
}
func (*MJHamburger) ProduceHamburger() string {
return "Produce: MJ Hamburger"
}
//抽象工厂
type FoodFactory interface {
CreatePizza() Pizza
CreateHamburger() Hamburger
}
//具体工厂
type KFCFactory struct{}
func (*KFCFactory) CreatePizza() Pizza {
return &KFCPizza{}
}
func (*KFCFactory) CreateHamburger() Hamburger {
return &KFCHamburger{}
}
type MJFactory struct{}
func (*MJFactory) CreatePizza() Pizza {
return &MJPizza{}
}
func (*MJFactory) CreateHamburger() Hamburger {
return &MJHamburger{}
}
func main() {
fmt.Println("hello")
var kfcfactory FoodFactory
kfcfactory = &KFCFactory{}
var mjfactory FoodFactory
mjfactory = &MJFactory{}
kfcPizza := kfcfactory.CreatePizza()
fmt.Println(kfcPizza.ProducePizza())
kFCHamburger := kfcfactory.CreateHamburger()
fmt.Println(kFCHamburger.ProduceHamburger())
mjPizza := mjfactory.CreatePizza()
fmt.Println(mjPizza.ProducePizza())
mjHamburger := mjfactory.CreateHamburger()
fmt.Println(mjHamburger.ProduceHamburger())
}
以上是关于GO设计模式05抽象工厂模式的主要内容,如果未能解决你的问题,请参考以下文章