1, describe,
Like the simple factory pattern, it is a creation pattern.
Define an interface for creating objects and let subclasses decide which class to instantiate.
Instead of a single factory creating all instances, concrete instances are created by a bunch of concrete factories that implement the factory interface, each of which can only create its own instance.
2, implementation,
Type Operator interface {Operate(int, Int AddOperator struct {} func (*AddOperator)Operate(a int, Type SubOperator struct {} func (*SubOperator)Operate(a int, B int) int{return a - b} OperatorFactory Interface {GetOperator() Operator} // Create operation factory type AddOperatorFactory struct {} func (*AddOperatorFactory)GetOperator() Operator{return &AddOperator{}} // Create a subtraction factory class type SubOperatorFactory struct {} func (*SubOperatorFactory)GetOperator() Operator{ return &SubOperator{} } func main() { var operatorFactory OperatorFactory operatorFactory = &AddOperatorFactory{} FMT. Println (operatorFactory. GetOperator (.) Operate (1, 3)) operatorFactory = & SubOperatorFactory {} FMT. Println (operatorFactory. GetOperator (.) Operate (1, 3)}Copy the code
Type IBaseFile Interface {IsSMSType() bool IsPayType() bool DownLoadFile()} // Define basic file information class type BaseFile struct {Uri String Temp String Content string} func (f *BaseFile)DownLoadFile() {f.tent = ""} // Implements product (file) class type CsvFile struct { BaseFile } func (*CsvFile)IsSMSType() bool { fmt.Println("csv file is sms type..." ) return true } func (*CsvFile)IsPayType() bool { fmt.Println("csv file is pay type..." ) return true } type ExeclFile struct { BaseFile } func (*ExeclFile)IsSMSType() bool { fmt.Println("execl file is sms type..." ) return true } func (*ExeclFile)IsPayType() bool { fmt.Println("execl file is pay type..." FileFactory struct {} func (c *FileFactory)CreateCsv() IBaseFile {return &CsvFile{}} func (c *FileFactory)CreateExecl() IBaseFile { return &ExeclFile{} } func main() { var filefactory FileFactory csvFile := filefactory.CreateCsv() csvFile.DownLoadFile() csvFile.IsSMSType() csvFile.IsPayType() execlFile := filefactory.CreateExecl() execlFile.DownLoadFile() execlFile.IsSMSType() execlFile.IsPayType() }Copy the code
3, summarize
We pull the factory class out of an interface that has only a factory method that creates an abstract product. All factories that produce concrete classes implement this interface. The factory class of such a simple factory becomes a factory abstract interface and a factory of several concrete production objects. When we want to add a new logical operation, we do not need to change the original factory class, but just add the operation class of this function and the corresponding factory class.