Simple factory pattern for Java design pattern learning

Simple factory mode

The simple factory mode is a creation mode, It is also called static factory method pattern, but it does not belong to one of the 23 GOF design patterns. Simple factory pattern is an instance of which product class is created by a factory object. Simple factory pattern is the simplest and most practical pattern in the factory pattern family, which can be understood as a special implementation of different factory patterns.

Design a calculator using simple factory mode.

1: Create a class of operations

2: Create an addition class.

3: Create a subtraction class.

4: Create a multiplication class.

5: Create a division class.

6: After the basic operation class is completed, you will find that you need to instantiate different classes according to the required addition, subtraction, multiplication and division. In this case, you need a factory class.

Factory classes create different objects according to different operations. Here is the use of polymorphism.

7: Test class

8: Console output:

result=3.0

Advantages: the simple factory class is the key of the whole pattern, which contains the necessary logical judgment. According to the external information, it determines which specific class object should be created. By implementing the simple factory pattern, the user does not need to know how the object is created, but just pass in the necessary information.

Disadvantages: the factory class centralizes the creation logic of all instances, which violates the high cohesion allocation principle. With the increasing number of specific product categories in the system, it is bound to constantly modify the factory category, which is difficult to maintain and expand. At the same time, it also violates the principle of opening and closing.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>