[Design pattern] ------ Contrast and summary: simple factory pattern, factory method pattern, abstract factory pattern

Three concepts:

Simple factory pattern: It is a simple factory class that returns subclass objects referenced by different parent classes according to different input parameter types.
Factory method pattern: It is the process of which subclass object will be generated until the factory subclass is implemented, and the factory parent class only defines the interface.
Abstract factory pattern: It is based on the factory method pattern, which factory subclass logic will be used, and then use the simple factory pattern to generate.

Mutual relationship

The factory method pattern is an improvement to the simple factory pattern.
The abstract factory pattern is an improvement to the factory method.

Pros and cons

The simple factory model is simple, but it does not comply with the opening and closing principle (new class, need to modify the factory class)

In order to solve the opening and closing principle of the simple factory model, the factory method model has emerged.
Factory method mode , new class does not need to modify the factory class, but may need to add the corresponding factory class. And there is not much connection between multiple factory classes, which is not easy to manage.

The abstract factory pattern manages multiple factory classes of the factory method pattern with simple factory pattern routines. But the disadvantage is that it is not simple. If you want to make it simple, use the simple factory pattern.

It can be seen that these three factory models, in order, each model is to solve the problem of the previous model, but at the same time there are new problems.

To give an inappropriate but very vivid example:

The background is the design of a module for Party B to provide Party A with a project.

At the beginning, Party B said that the simple factory model was used, but Party A said that it was not good.
Then after improvement, Party B said to use the factory method model. Party A hesitated for a while and said that it could be better.
Then Party B improved it again, so let's use the abstract factory pattern. Party A looked at it for a long time, and nodded and said, good is good, but it is a bit complicated, and it may be difficult to maintain later.

In the end, Party A used the first version of the simple factory model.

Refer to the separate introduction of the three factory design patterns:

Simple factory pattern
Factory method pattern
Abstract factory pattern

Published 203 original articles · praised 186 · 210,000 views

Guess you like

Origin blog.csdn.net/java_zhangshuai/article/details/105213563