Design Patterns-simple factories, factory methods, and abstract factories
Simple factory, factory method, and abstract factory are all three design patterns that help us extract the instantiation part of objects, optimize the system structure, and are often used in development. There are both differences and connections between the three. Today we will make a simple record of these three design patterns.
Overview simple factory: used to produce any product in the same level structure (for new products, you need to modify the factory) Factory method: abstract Factory used to produce fixed products in the same level structure (support for adding new products): used to produce all products of different product families (support for adding new product families, new products are not supported.) simple factory
In general, a static method is used to set the createProduct method to static and pass the required product type to the function parameter (type ), use switch/case in the method to help us create a Product ).
For this method, if we want to add a new Product, first we need to implement the Product interface, and then we need to modify the createProduct method under SimpleFactory.
Factory method
We can see that, unlike a simple factory, each of our FactoryMethod implementation classes generates only one product, that is, a fixed product is generated here.
To add a new Product, we only need to implement the Product interface and create a new FactoryMethod implementation class to help us create the Product without modifying other code.
Abstract Factory
? Gu @>? Gu A: w "http://www.bkjia.com/net/router/" target = "_ blank" class = "keylink"> two series of router products, then Huawei and ZTE correspond to A and B, mobile phones and routers correspond to One and Two.
In this way, we want to add a new product family, that is, to create a new series of Three, we only need to create FactoryThree to implement AbstractFactory, and add a new series of products under the corresponding brand. But we need to change the code when we need to add a new brand.