其他分享
首页 > 其他分享> > 工厂方法模式

工厂方法模式

作者:互联网

工厂方法模式

咖啡接口

package factoryMethod

type coffer interface{
    addMilk()
	addSugar()
	getName() string
}

咖啡

package factoryMethod

type coffee struct{
    name string
}

中式咖啡

package factoryMethod

type chinaCoffee struct {
    coffee
}

func NewChinaCoffee() *chinaCoffee{
    cof := new(chinaCoffee)
    cof.name = "中式咖啡"
    return cof
}

func (c *chinaCoffee)addMilk(){
    fmt.Println("加入三分之一汤匙牛奶!")
}

func (c *chinaCoffee)addSugar(){
    fmt.Println("加入10克白糖!")
}

func (c *chinaCoffee)getName() string{
    return c.name
}

美式咖啡

package factoryMethod

type americanCoffee struct {
    coffee
}

func NewAmericanCoffee() *americanCoffee{
    cof := new(americanCoffee)
    cof.name = "美式咖啡"
    return cof
}

func (a *americanCoffee)addMilk(){
    fmt.Println("加入一汤匙牛奶!")
}

func (a *americanCoffee)addSugar(){
    fmt.Println("加入20克白糖!")
}

func (a *americanCoffee)getName() string{
    return a.name
}

工厂方法接口

package factoryMethod

type factoryMethod interface{
    createCoffee() coffer
}

中式咖啡工厂

package factoryMethod

type ChinaCoffeeFactory struct{}

func NewChinaCoffeeFactory() *ChinaCoffeeFactory{
    return new(ChinaCoffeeFactory)
}

func(c *ChinaCoffeeFactory)createCoffee() coffer{
    ccof := NewChinaCoffee()
    ccof.addMilk()
    ccof.addSugar()
    
    return ccof
}

美式咖啡工厂

package factoryMethod

type AmericanCoffeeFactory struct{}

func NewAmericanCoffeeFactory() *AmericanCoffeeFactory{
    return new(AmericanCoffeeFactory)
}

func(a *AmericanCoffeeFactory)createCoffee() coffer{
    acof := NewAmericanCoffee()
    acof.addMilk()
    acof.addSugar()
    
    return acof
}

咖啡店

package factoryMethod

type coffeeStore struct {
    factory factoryMethod
}

func NewCoffeeStore(factory factoryMethod) *coffeeStore{
    fac := new(coffeeStore)
    fac.factory = factory
    
    return fac
}

func (c *coffeeStore)orderCoffee() coffer{
    return c.factory.createCoffee()
}

测试文件

package factoryMethod

func TestFactoryMethod(t *testing.T){
    store := NewCoffeeStore(NewChinaCoffeeFactory())
    cof := store.orderCoffee()
    fmt.Println(cof.getName())
    
    store1 := NewCoffeeStore(NewAmericanCoffeeFactory())
    cof := store.orderCoffee()
    fmt.Println(cof.getName()) 
}

标签:return,package,type,factoryMethod,模式,工厂,func,cof,方法
来源: https://www.cnblogs.com/mathsmouse/p/16671594.html