Java designer pattern simple factory pattern parsing
brief introduction
Simple factory mode is also called static factory method mode.
Simple factory mode usually defines a factory class, which can return different product instances according to different variables.
The simple factory pattern is an object creation pattern, but the simple factory pattern does not belong to one of the 23 GOF design patterns.
example
How to implement a calculator with basic functions of addition, subtraction, multiplication and division?
For these four operations, two operands are required. The only difference is that the results returned are different.
Thus, we can abstract their commonness and extract a parent class. This class contains two operands and a method that returns the result, which is expected to be implemented in a subclass.
The following is explained by specific code.
Product (operation): product role, the parent class of all objects created by the simple factory pattern, which is responsible for describing the common interface shared by all instances.
Concreteproduct group: a specific product role that implements the interface in the product.
Factory (operationfactory): the factory role, the core of the simple factory pattern, is responsible for implementing the internal logic of creating all instances. The method of creating product class of factory class can be directly called by the outside world to create the required product object.
Test code
Operation results
main points
advantage
The factory class of simple factory pattern is the key of the whole pattern. It contains the necessary logical judgment to determine which specific class object should be created according to the external information.
By using the simple factory pattern, users do not need to know how objects are created, but just pass in the necessary information.
shortcoming
The factory class centralizes the creation logic of all instances, which violates the principle of high cohesion and responsibility allocation.
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.
summary
The above is all about the simple factory pattern parsing of Java designer pattern in this paper. I hope it will be helpful to you. Interested friends can continue to refer to this site: Visitor mode usage scenarios and code examples of Java design patterns, abstract factory code examples of Java design pattern notes, etc. if you have any questions, you can leave a message at any time. Xiaobian will reply to you in time. Thank you for your support!