Intent:
• Define a class to create instances of other classes. The created instance usually has a common parent class. • The (simple factory) mode is also called the static factory method mode. It belongs to the class creation mode. Generally, it returns instances of different classes based on different independent variables. • In simple factory mode, a factory class dynamically determines which product class instance should be created based on input parameters. • The simple factory mode does not actually belong to 23 gof models, but it can be used as a guide to the factory method mode.
UML diagram:
Roles and responsibilities in this mode:
Factory (simplefactory) Role
The core of the simple factory mode is to implement the internal logic for creating all instances. The factory class can be directly called by the outside world to create the required product objects.
Abstract Product role
The parent class of all objects created in simple factory mode, which describes the common public interfaces of all instances.
Product (Concrete Product) Role
Is the creation target of the simple factory mode. All created objects are instances of a specific class that acts as this role.
Advantages and disadvantages:
Advantages
• The factory class is the key to the entire model. it contains the necessary logical judgment to determine which class object should be created based on the information given by the outside world. by by using the factory class, the outside world can get rid of the embarrassing situation of directly creating specific product objects. You only need to be responsible for "consuming" objects. you don't have to worry about how these objects are created and organized. clarify their respective responsibilities and rights, which is conducive to the optimization of the entire software architecture. disadvantages • because the factory class integrates the creation logic of all instances, it violates the High Cohesion responsibility allocation principle and integrates all creation logic into a factory class. • When the number of product categories in the system increases, the requirements for the factory category to create different instances based on different conditions may arise. this kind of judgment on the condition is intertwined with the judgment on the specific product type. It is difficult to avoid the spread of module functions, which is very unfavorable for system maintenance and expansion. (In violation of OCP Principles) • These these shortcomings have been overcome in the factory method mode. • The factory class is responsible for creating fewer objects. • The customer only knows the parameters passed into the factory class, do not care about how to create objects (logic) • because a simple factory can easily violate the High Cohesion responsibility allocation principle, it is generally applied only in simple cases.