Factory pattern of design pattern

Basic definition

The factory method pattern defines an interface for creating objects, but the subclass determines which class to instantiate. The factory method pattern defers instantiation to subclasses.

Pattern structure

Product: Abstract product. All products must implement this common interface, so that the classes that use these products can both reference this interface.

ConcreteProduct: specific products.

Creator: Abstract factory. It implements all methods of manipulating products, but does not implement factory methods. All subclasses of Creator must implement the factoryMethod () method.

ConcreteCreator: concrete factory. The actual factory that manufactures the product. It is responsible for creating one or more specific products.

 

Mode realization:

Product Abstract Product

 

ConcreteProduct

 

 

Factory abstract factory class

 

ConcreteFactory

 

Test class

 

Results of the

09: 46: 41.447 [main] INFOcom.yanyuan.gof.build.factory.v2.HuaweiPhone-Huawei mobile phone to dial Diao Chan

09: 46: 41.463 [main] INFOcom.yanyuan.gof.build.factory.v2.IPhone-iPhone phone calls Xiaoqiao

Pros and cons

advantage

In the factory method, the user only needs to know the specific factory of the desired product, and does not need to relate to the specific creation process, or even the name of the specific product class.

When adding new products to the system, we only need to add a specific product category and implementation factory, without any modification to the original factory, which is in good compliance with the "opening and closing principle"

Disadvantages

Each time you add a product, you need to add a specific class and object to realize the factory. The number of classes in the system will increase exponentially, which increases the complexity of the system to a certain extent, and also increases the dependence of the specific classes of the system.

to sum up

The factory method model fully complies with the "opening and closing principle"

The factory method pattern uses inheritance to delegate objects to subclasses and implement factory methods through subclasses to create objects

In the factory method pattern, the creator usually contains product code that depends on abstraction, and these abstract products are created by subclasses. The creator does not need to know which specific product to make

 

Guess you like

Origin www.cnblogs.com/xueSpring/p/12736414.html