The simple factory pattern, also known as the static factory method, is a design pattern in which a factory object determines the instance of a certain object class to be created. This type of design pattern belongs to the creational patterns, and in the simple factory pattern, instances of different classes can be returned based on different parameters. The simple factory pattern specifically defines a class responsible for creating instances of other classes, and the created instances usually have a common parent class.
The purpose of the simple factory pattern is to define an interface for creating objects and let its subclasses decide which factory class to instantiate. The factory pattern defers the creation process to the factory method, mainly solving the interface selection problem, with its subclasses implementing the factory interface, returning an abstract product.
Factory: Factory role, responsible for implementing the internal logic of creating all instances.
Product: Abstract product role, representing the parent class of all created objects, responsible for describing the common interface shared by all instances.
ConcreteProduct: Concrete product role, representing the created target. All created objects act as instances of a specific class in this role.
The factory class contains necessary decision logic, which can determine when to create an instance of which product class. The client can be exempt from the direct responsibility of creating product objects, only consuming the products. The simple factory pattern achieves a division of responsibilities through this approach, providing a dedicated factory class for object creation.
The client does not need to know the specific class name of the created product, only needing to know the parameters corresponding to the specific product class. For some complex class names, the use of the simple factory pattern can reduce the amount of memorization for the user.
By introducing a configuration file, it is possible to replace and add new specific product classes without modifying any client code, to a certain extent, improving the flexibility of the system.
Since the factory class concentrates all product creation logic, if it fails to work properly, the entire system will be affected.
Using the simple factory pattern will increase the number of classes in the system, to a certain extent, increasing the complexity and difficulty of understanding the system.
System expansion difficulties. Once a new product is added, the factory logic has to be modified, and in the case of many product types, it may lead to overly complex factory logic, making it difficult to extend and maintain the system.
Because the simple factory pattern uses static factory methods, the factory role cannot form an inheritance-based hierarchy.