This article comes from Introduction to Java video tutorial Courseware.
- Factory mode
It realizes the separation of creator and caller, that is, the specific process of creating objects is shielded and isolated, so as to improve flexibility. In fact, both design patterns and object-oriented design principles are to make the development project easier to expand and maintain. The solution is a "division of labor".
1. Object oriented design principles
1.1 OCP (open closed principle)
- A software entity should be open to extensions and closed to modifications.
- When we finish writing the code, we can't modify it because the requirements change. We can solve the changing needs by adding new code. If the original code is modified every time the demand changes, there is a risk that the original code will be modified incorrectly. Of course, there is a risk that intentional and unintentional modifications will lead to the failure of the original normal operation functions. In this way, it is likely to launch a terrible butterfly effect and increase the maintenance work sharply.
- In the final analysis, in addition to the strong scalability on the surface, the opening and closing principle pays more attention to the maintenance cost in the enterprise
- Therefore, the opening and closing principle is the first principle of the design mode. Its subtext is to control the risk of demand change and reduce the maintenance cost.
1.2 DIP (dependency inversion principle)
- Program for the interface, not for the implementation.
- If B is associated in A, try to make B implement an interface, and then A has A relationship with the interface, not with the B implementation class.
- The subtext of dependency inversion is: oriented to abstract programming, decoupling the caller and callee.
1.3 LOD (Law Of Demeter)
- Only communicate with your direct friends and avoid communicating with strangers.
- It is required to be encapsulated as much as possible, independent as much as possible, and use low-level access modifiers as much as possible. This is a typical embodiment of packaging characteristics.
- If a class exposes too many private methods and fields, the caller will be at a loss. And it will cause unnecessary judgment code to the class. Therefore, we use the access modifier as low as possible to let the outside world know our interior. This is also the basic idea of object-oriented. This is a feature of the Dimitri principle, and you can't know more private information about classes.
- In addition, the Demeter principle requires that there should be as few direct links between classes as possible, and the access of the two classes should be through the second step
Three mediation classes. - The subtext of Dimitri's principle is: don't talk to strangers and go to intermediaries.
2. Classification of plant mode
- Simple factory mode: used to produce any product in the same hierarchical structure. (for adding new products, the existing code needs to be modified)
- Factory method mode: used to produce fixed products in the same hierarchical structure. (any product can be added)
- Abstract factory pattern: used to produce all products of different product families. (for adding new products, none)
Can do something; Support adding product family)
In the book design patterns, GOF divides factory patterns into two categories: Factory Method Pattern and abstract factory pattern. The simple factory pattern is regarded as a special case of the factory method pattern, and the two fall into one category.
- Core essence
Instantiate the object and replace the new operation with the factory method.
Implementation classes will be selected and objects created for unified management and control. This decouples the caller from our implementation class.
2.1 no factory mode
package pers.chh3213.classLearn20220101exercise; interface Car{ void run(); } class Audi implements Car{ public void run() { System.out.println("Audi is running"); } } class BYD implements Car{ public void run() { System.out.println("BYD is running"); } } public class Client01 { public static void main(String[] args) { Car a = new Audi(); Car b = new BYD(); a.run(); b.run(); } }
2.2 simple factory mode
- Simple factory mode. From the naming, we can see that this mode must be very simple. It exists for a simple purpose: to define a factory class for creating objects
package pers.chh3213.classLearn20220101exercise; interface Car{ void run(); } class Audi implements Car{ public void run() { System.out.println("Audi is running"); } } class BYD implements Car{ public void run() { System.out.println("BYD is running"); } } //Factory class class CarFactory { //Mode 1 public static Car getCar(String type) { if ("audi".equals(type)) { return new Audi(); } else if ("BYD".equals(type)) { return new BYD(); } else { return null; } } //Mode II //public static Car getAudi() { //return new Audi(); //} // //public static Car getByd() { //return new BYD(); //} } public class Client02 { public static void main(String[] args) { Car a = CarFactory.getCar("audi"); a.run(); Car b = CarFactory.getCar("BYD"); b.run(); } }
- As long as the caller knows what he wants, where to get it and how to create it, he doesn't need to know. Division of labor, an additional factory class specializing in the production of Car implementation class objects. Separate the caller from the creator.
- Summary:
- Simple factory mode is also called static factory mode, that is, factory classes generally use static methods to return different instance objects through different received parameters.
- Disadvantages: for adding new products, it cannot be extended without modifying the code. Violation of the opening and closing principle (open to expansion; closed to modification).
2.3 factory method mode
- In order to avoid the disadvantages of simple factory mode, OCP is not fully satisfied (open to extension and closed to modification). The biggest difference between the factory method pattern and the simple factory pattern is that the simple factory pattern has only one factory class (for a project or an independent module), while the factory method pattern has a group of factory classes that implement the same interface. In this way, the pressure on factory methods in the simple factory mode can be shared by different factory subclasses in the factory method mode.
package pers.chh3213.classLearn20220101exercise; interface Car{ void run(); } class Audi implements Car{ public void run() { System.out.println("Audi is running"); } } class BYD implements Car{ public void run() { System.out.println("BYD is running"); } } //Factory interface interface Factory{ Car getCar(); } //Two factory classes class AudiFactory implements Factory{ public Audi getCar(){ return new Audi(); } } class BydFactory implements Factory{ public BYD getCar(){ return new BYD(); } } public class Client03 { public static void main(String[] args) { Car a = new AudiFactory().getCar(); Car b = new BydFactory().getCar(); a.run(); b.run(); } }
- summary
- Simple factory mode and factory method mode really avoid code changes? No,
- In the simple factory mode, the judgment statement in the factory role should be modified for the addition of new products; In the factory method pattern, either the judgment logic is left in the abstract factory role, or the specific factory role is written dead in the client program (as in the above example). Moreover, the change of product object creation conditions will inevitably lead to the modification of factory role. In the face of this situation, the ingenious combination of Java reflection mechanism and configuration file breaks through the limitation - which is perfectly reflected in Spring.
2.4. Abstract factory mode
- The difference between the abstract factory pattern and the factory method pattern lies in the complexity of creating objects. Moreover, the abstract factory pattern is the most abstract and general of the three.
- The purpose of the abstract factory pattern is to provide an interface for the client to create product objects in multiple product families.
- In addition, the following conditions must be met when using the abstract factory pattern:
1) There are multiple product families in the system, and the system can only consume one family of products at a time.
2) Products belonging to the same product family are used by them.