在项目过程中,遇到某处需要使用工厂模式,因此写了个测试代码进行测试,
- 首先定义了interface Worker,其中包含一个接口Work(task *string)
- 然后定义创建Worker的interface WorkerCreator,包含一个接口Create() ,返回值为Worker
type Worker interface {
Work(task *string)
}
type WorkerCreator interface {
Create() Worker
}
我们假设有一个工种程序员,实现了Work接口,同时定义其构造类,实现Create()接口
type Programmer struct {
}
func (p *Programmer) Work(task *string) {
fmt.Println("Programmer process", *task)
}
type ProgrammerCreator struct {
}
func (c *ProgrammerCreator) Create() Worker {
s := new(Programmer)
return s
}
再设想一种工种农场主:
type Farmer struct {
}
func (f *Farmer) Work(task *string) {
fmt.Println("Farmer process", *task)
}
type FarmerCreator struct {
}
func (c *FarmerCreator) Create() Worker {
s := new(Farmer)
return s
}
编写测试代码
func main() {
var c WorkerCreator
c = new(ProgrammerCreator)
p := c.Create()
taskProject := "Project"
p.Work(&taskProject)
c = new(FarmerCreator)
f := c.Create()
taskFarmland := "farmland"
f.Work(&taskFarmland)
}
有疑问加站长微信联系(非本文作者)