Home > Article > Backend Development > Practice and discussion of factory pattern in Golang
Factory pattern is a design pattern used to create objects without specifying specific classes. Its advantages include decoupling the creation process, scalability and flexibility. It is suitable for complex creation processes, the need to dynamically select products, or the need to provide Situation where new product type capabilities are created.
Factory pattern is a design pattern used to create objects. No need to specify a specific class. It allows the application to obtain the required object without knowing the creation process.
type Product interface { DoSomething() } type ProductA struct {} func (p *ProductA) DoSomething() { fmt.Println("ProductA doing something...") } type ProductB struct {} func (p *ProductB) DoSomething() { fmt.Println("ProductB doing something...") } type Factory interface { CreateProduct() Product } type FactoryA struct {} func (f *FactoryA) CreateProduct() Product { return &ProductA{} } type FactoryB struct {} func (f *FactoryB) CreateProduct() Product { return &ProductB{} } func main() { factoryA := &FactoryA{} productA := factoryA.CreateProduct() productA.DoSomething() // Output: ProductA doing something... factoryB := &FactoryB{} productB := factoryB.CreateProduct() productB.DoSomething() // Output: ProductB doing something... }
The factory pattern is often used to decouple the creation process and the use of objects. For example, when using a dependency injection framework, it allows you to create objects without directly relying on concrete classes.
Situations when considering using the factory pattern include:
The above is the detailed content of Practice and discussion of factory pattern in Golang. For more information, please follow other related articles on the PHP Chinese website!