This is a creation in Article, where the information may have evolved or changed.
In the course of the project, we encountered a need to use Factory mode, so I wrote a test code to test it.
- The interface Worker is defined first, which contains an interface work (Task *string)
- Then define the interface workercreator that creates the worker, which contains an interface of Create (), and the return value is worker
typeinterface { Work(task *string)}typeinterface { Create() Worker}
We assume that there is a job programmer that implements the work interface and defines its construction class to implement the Create () interface
typestruct {}func (p *Programmer) Work(task *string) { fmt.Println("Programmer process", *task)}typestruct {}func (c *ProgrammerCreator) Create() Worker { new(Programmer) return s}
Then imagine a type of farmer:
typestruct {}func (f *Farmer) Work(task *string) { fmt.Println("Farmer process", *task)}typestruct {}func (c *FarmerCreator) Create() Worker { new(Farmer) return s}
Writing test Code
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)}