Abstract Factory Pattern and Factory Pattern

During the chat with my colleagues today, I talked about the factory model, and I am ashamed to have almost forgotten it, only a little bit.

Decisively read the information to consolidate it.

First of all, let’s talk about the factory mode. The factory mode can be described as a product interface, corresponding to multiple product implementation classes, and then a factory class, which generates a specific implementation class based on the incoming value judgment (which can be generated by new or by reflection based on the class name path) ). But there is a disadvantage that whenever a new product is added, not to mention the product real class, the code needs to be modified in the factory class.

At this time, I have to mention the factory method pattern (a typical template pattern). On the basis of the factory pattern, an abstract factory interface will be abstracted, and the concrete implementation classes will correspond to a factory implementation class. The advantage of this is that even if a new product is added, only the You need to add a product-implemented class and a factory-implemented class. It fully implements the OCP (Open-Closed Principle).

The abstract factory model is further based on the factory method model. It is aimed at different products, that is, product families. For example, the recently popular PUBG Mobile has different guns. M416 uses M416 gun handles and M416 bullets respectively; AKM uses AKM Gun handle and AKM bullets.

Then firstly, two product factory interfaces are required, namely the gun handle factory interface and the bullet factory interface.

The gun handle factory interface has two implementation classes, which are M416 gun handle factory and AKM gun handle factory.

Secondly, the bullet factory interface has two implementation classes, namely M416 bullet factory and AKM bullet factory.

Then you need an abstract factory interface, which contains two abstract methods of gun handle and bullet

Secondly, there are two implementation classes, the M416 implementation class contains two methods, M416 gun handle and M416 bullet

The AKM implementation class contains two methods, AKM handle and AKM bullet.

In general, the abstract factory pattern is aimed at products of different levels, and if they belong to the same level, it is a factory pattern.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325105760&siteId=291194637