Simple factories, factory methods and abstract factories three design patterns are used to help us extract the instanced parts of objects, optimize the system structure, and use them frequently in development. There are both differences and links, today to make a simple record of these three design patterns.
Overview
- Simple factory: Used to produce any product in the same hierarchy (for adding new products, modifications to the plant are required)
- Factory method: Used to produce fixed products in the same hierarchy (support for adding new products)
- Abstract Factory: Used to produce all products of different product families (support to add new product families, do not support the addition of new products)
Simple Factory
In general, with a static method, the Createproduct method is set to static, the product type we need is passed into the function parameter (type), and within the method we use Switch/case to help us create the product.
In this way, if we want to add new products, we first need to implement the product interface, and then we need to modify the Createproduct method under Simplefactory.
Factory method
It can be seen that unlike a simple factory, each of our FactoryMethod implementation classes only produces a single product, that is, this is the generation of fixed products.
For adding new products, we simply implement the product interface and create a new FactoryMethod implementation class to help us create the product without needing to modify other code.
Abstract Factory
For abstract factories, it is used to produce all products of different product families. As you can see, producta and PRODUCTB are two different brands, and these two brands have two products of the same type one and two. For example, Huawei and ZTE are two different brands, each of which manufactures two series of products for mobile phones and routers, so Huawei and ZTE correspond to A and B, while phones and routers correspond to one and two.
So we want to add a new product family, a new series three, just create a factorythree implementation abstractfactory, and add a new series of products under the respective brands. But when we need to add a new brand, we need to change the code.
Design patterns-Simple factories, factory methods and abstract factories