golang 工厂模式

79 阅读1分钟

需求,一个店可以卖鸡和鱼,通过工厂实现


package main

import (
   "fmt"
)

type Foods interface {
   Display()
}
type Duck struct {
   price int
}
type Fish struct {
   price int
}

func (h Fish) Display() {
   fmt.Println("I'm Fish, price is ", h.price)
}

func (p Duck) Display() {
   fmt.Println("I'm Duck, price is ", p.price)
}

func (h Fish) GetFood() Foods {
   return &Fish{price: 10}
}
func (p Duck) GetFood() Foods {
   return &Duck{price: 20}
}
func main() {
   h := Fish{}
   fish := h.GetFood()
   fish.Display()
   p := Duck{}
   duck := p.GetFood()
   duck.Display()
}