package Factory
import "fmt"
type Restaurant interface {
GetFood()
}
type Donglaishun struct {
}
func (d *Donglaishun) GetFood() {
fmt.Println("东来顺的饭菜准备继续")
}
type Qingfeng struct {
}
func (q *Qingfeng) GetFood() {
fmt.Println("庆丰包子铺饭菜准备就绪")
}
func NewRestaurant(s string) Restaurant {
switch s {
case "d":
return &Donglaishun{}
case "q":
return &Qingfeng{}
}
return nil
}
test
package Factory
import "testing"
func TestNewRestaurant(t *testing.T) {
NewRestaurant("d").GetFood()
NewRestaurant("q").GetFood()
}
在代码中我们使用了一个 interface 我们可以理解成工厂
在东来顺中, 就做东来顺的菜 , 在庆丰包子铺中就做包子铺的食物
我们传进标志, 会返回 具体的工厂
, 然后执行方法, 就会生产
手机扫一扫
移动阅读更方便
你可能感兴趣的文章