乐趣区

关于设计模式:设计模式简单工厂模式

工程目录

factory.go

package Factory

import "fmt"

type Factory interface {Generate()
}

type Phone struct {

}

type Computer struct {

}

func (p *Phone) Generate(){fmt.Println("生产了一部手机")
}

func (c *Computer) Generate() {fmt.Println("生产了一台电脑")
}

func NewFactory (name string) Factory {
    switch name {
    case "phone":
        return &Phone{}
    case "computer":
        return &Computer{}}
    return nil
}

factory_test.go

package Factory

import "testing"

func TestNewFactory(t *testing.T) {NewFactory("phone").Generate()
    NewFactory("computer").Generate()}
退出移动版