1. Steps to use
- Create abstract/Interface product classes, define common interface methods for specific products; ( product Interface class )
- Create a specific product class, which inherits the abstract product class; ( product Interface implementation class )
- Create a factory class to create instances of different product classes by creating static methods based on passing in different parameters; ( factory class , creating specific product instances)
- The outside world can create instances of different product classes by invoking the static methods of the factory class and passing in different parameters. ( use the class to get the desired product instance using the factory class)
2. Advantages
- Separating the work of creating an instance from the work of using an instance, the consumer does not have to care about how the class object is created, and how it is decoupled; ( creating objects and separating with objects )
- The work of initializing instances is put into the factory, making the code easier to maintain. More in line with object-oriented principles, interface-oriented programming, rather than implementation-oriented programming. ( interface-oriented programming )
3. Disadvantages
- The factory class centralizes the creation logic of all instances (products), and the entire system is affected once the factory fails to function properly.
- Violating the open-close principle, once a new product is added, you have to modify the logic of the factory class, which makes the factory logic too complex.
- Simple Factory mode because static factory methods are used, static methods cannot be inherited and rewritten, resulting in the inability of factory roles to form inheritance-based hierarchies.
4. Application Scenarios
After understanding the pros and cons, we learned about the simple factory model scenario:
- If the customer only knows the parameters of the incoming factory class, and does not care about how to create the object's logic;
- When the factory class is responsible for creating objects (specific products) less.
The Simple Java Factory