Applicable occasions:
7.3 Applicable occasions for factory model
The easiest way to create a new object is to use the new keyword and concrete classes. Only on some occasions can the extra complexity of creating and maintaining an object factory be worth the money. This section summarizes these occasions.
7.3.1 Dynamic implementation
If you need to create objects that implement the same interface in different ways, like the previous bicycle example, you can use a factory method or a simple factory object to simplify the process of selecting implementation. This choice can be made explicitly or implicitly. The former is like the bicycle example, and the customer can choose the bicycle model you need; while the XHR factory example mentioned in the next section belongs to the latter. The type of connection object returned in this example depends on the detected bandwidth and network delay factors. In these situations, you usually have to deal with a series of classes that implement the same interface and can be treated equally. This is the most common reason for using factory pattern in JavaScript.
7.3.2 Save settings overhead
If objects need to be complex and relevant to each other, using factory mode can reduce the amount of code required for each object. This effect is particularly prominent if this setting only needs to be performed once for all instances of a particular type. Putting this setting code into the class constructor is not an efficient approach, because even if the setting work is completed, the code will still be executed every time a new instance is created, and doing so will distribute the setting code into different classes. The factory method is perfect for this occasion. It can be set at once before instantiating all required objects. No matter how many different classes are instantiated, this method can keep the setup code in one place.
This is especially useful if the class used requires the external library to be loaded. Factory methods can check these libraries and dynamically load those not found. These settings codes exist in only one place, so it is much more convenient to modify them later.
7.3.3 Make a large object with many small objects
The factory method can be used to create objects that encapsulate many smaller objects. Consider the constructor of the bicycle object. Bicycles contain many smaller subsystems: wheels, frames, transmission components, and brakes. If you don't want a strong coupling between a subsystem and a larger object, but want to pick from many subsystems at runtime, then the factory approach is an ideal choice. Using this technology, you can one day match all the bikes you sell with some kind of chain, and if you find another more favorite chain the next day, you can use this new variety instead. It's easy to implement this change because the constructors of these bicycle classes do not depend on a particular chain variety. The RSS reader example later in this chapter demonstrates the use of the factory model in this regard.
The factory pattern mainly provides an interface for creating objects. The factory model is divided into three categories according to the terms in "Java and Pattern":
1. Simple Factory
2. Factory Method
3. Abstract Factory
These three patterns are gradually abstract from top to bottom and are more general. There is also a classification method, which is to regard the simple factory model as a special case of the factory method model, and the two are classified into the same category. Here are two situations where factory mode is used:
1. When encoding, you cannot foresee what kind of instances you need to create.
2. The system should not rely on details on how product class instances are created, combined and expressed
3. Simple factory model
As the name suggests, this model itself is simple and is used in situations where the business is simpler.
It consists of three roles (see the class diagram below for the relationship):
1. Factory role: This is the core of this model, which contains certain business logic and judgment logic. In java it is often implemented by a concrete class.
2. Abstract product role: It is generally a parent class inherited by a specific product or an interface implemented. Implemented by interfaces or abstract classes in Java.
3. Specific product role: The object created by the factory class is an instance of this role. Implemented by a concrete class in java.
So how to use the simple factory model? Let me give you an example. I think this is much easier to understand than a long theoretical text description! Here is the treatment for the nouveau riche: P
After using the simple factory model, the nouveau riche now only needs to sit in the car and say to the driver: "Driving". Let's see how it is implemented:
//Abstract product role public interface Car{ public void drive(); } //Specific product role public class Benz implements Car{ public void drive() { System.out.println("Driving Benz "); } } public class Bmw implements Car{ public void drive() { System.out.println("Driving Bmw "); } } . . . (I won't write Audi :P) //Factory class role public class Driver{ //Factory method//Note that the return type is abstract product role public static Car driverCar(String s)throws Exception { //Judge logic, return the specific product role to Client if(s.equalsIgnoreCase("Benz")) return new Benz(); else if(s.equalsIgnoreCase("Bmw")) return new Bmw(); ...... else throw new Exception(); . . . //Welcome the nouveau riche to appear... public class Magnate{ public static void main(String[] args){ try{ //Tell the driver that I am taking a Mercedes-Benz Car car = Driver.driverCar("benz"); //Give the command: drive(); . .If you put all the classes in one file, don't forget that only one class is declared public. The relationship between classes in a program is as follows:
This is the simple factory model. Here are the benefits:
First of all, after using the simple factory model, our program is not "ill" and is more in line with the reality; and the client is exempted from the responsibility of directly creating product objects, but is only responsible for "consuming" products (as the nouveau riche does).
Let’s analyze the simple factory model from the principle of opening and closing. When the nouveau riche adds a car, as long as it meets the contract formulated by the abstract product, it can be used by the customer as long as it is notified to the factory. So for the product part, it conforms to the principle of opening and closing - opening for expansion and closing for modification; but the factory part seems to be not ideal, because every time a car is added, corresponding business logic and judgment logic must be added to the factory class, which naturally violates the principle of opening and closing.
For such a factory class (in our case for the driver), we call it the Almighty class or the God class.
The example we give is the simplest case, and in practical applications, it is likely that the product is a multi-level tree structure. Since there is only one factory class in the simple factory model to correspond to these products, this may ruin our God class and in turn exhaust our lovely programmers:(
As I mentioned earlier, the simple factory model is suitable for situations where the business will be simple. But it may not be very adaptable to complex business environments. This should be done by the factory method model! !
4. Factory method model
Let's take a look at its composition first:
1. Abstract factory role: This is the core of the factory method pattern, it has nothing to do with the application. It is an interface that a specific factory role must implement or a parent class that must be inherited. In java it is implemented by abstract classes or interfaces.
2. Specific factory role: It contains code related to specific business logic. Called by the application to create the corresponding specific product object. In java it is implemented by concrete classes.
3. Abstract product role: It is the parent class inherited by a specific product or an interface implemented. In Java, there are generally abstract classes or interfaces to implement them.
4. Specific product role: The object created by a specific factory role is an example of this role. Implemented by concrete classes in Java.
Use class diagrams to clearly represent the relationship between them:
Let's use a complete example to see how the various roles in the factory model are coordinated. Speaking of the nouveau riche business, the more and more cars they love. This made the driver suffer. He had to remember and maintain any car, and he had to use it! So the nouveau riche sympathized with him and said: It depends on your years with me, you won’t have to work so hard in the future. I will assign you a few staff members, just take care of them! Therefore, the management of the factory method model emerged. The code is as follows:
//Abstract product roles, the specific product roles are similar to the simple factory model, but they have become a little more complicated, here is a bit omitted. //Abstract factory role public interface Driver{ public Car driverCar(); } public class BenzDriver implements Driver{ public Car driverCar(){ return new Benz(); } } public class BmwDriver implements Driver{ public Car driverCar() { return new Bmw(); } } ......//It should form a corresponding relationship with the specific product, here... //Ask Mr. Nouveaux public class Magnate { public static void main(String[] args) { try{ Driver driver = new BenzDriver(); Car car = driver.driverCar(); car.drive(); }catch(Exception e) { } } }The factory method uses an abstract factory role as the core instead of using concrete classes as the core in a simple factory pattern. Let's take a look at what the factory method model has brought us? Use the principle of opening and closing to analyze the factory method model. When a new product (i.e., the car of the nouveau riche) is generated, as long as it is generated according to the contract provided by the abstract product role and the abstract factory role, it can be used by the customer without having to modify any existing code. It seems that the factory method model is fully in line with the principle of opening and closing!
Using the factory approach model is enough to cope with most of the business needs we may encounter. However, when there are many types of products, a large number of corresponding factory categories will appear, which should not be what we hope. So I suggest using a simple factory pattern in this case combined with the factory method pattern to reduce the factory class: that is, using a simple factory pattern for similar species on the product tree (usually those that are brothers in the leaves of the tree).
Of course, special circumstances need to be treated with special treatment: for different product trees in the system and there are product families on the product trees, then in this case, the abstract factory model may be used.
5. Summary
Let’s take a look at the inspiration given by the simple factory model and factory method model:
If we don't use factory pattern to implement our example, maybe the code will be much less - just implement the existing car, without using polymorphism. But in terms of maintainability, scalability is very poor (you can imagine the class you want to touch after adding a car). Therefore, in order to improve scalability and maintenance, it is worth writing more code.
6. Abstract factory pattern
Let’s first understand what a product family is: a family of products composed of functions that are located in different product hierarchies and structures. If you can clearly understand this concept by just reading this sentence, I have to admire you. Let's use an example to illustrate it vividly.
BmwCar and BenzCar in the figure are two product trees (product hierarchy); while BenzSportsCar and BmwSportsCar as shown in the figure are one product family. They can all be placed in the sports car family, so the functions are related. Similarly, BmwBussinessCar and BenzSportsCar are also the same product family.
Going back to the topic of abstract product model, it can be said that the difference between it and the factory method model lies in the complexity of the need to create objects. Moreover, the abstract factory model is the most abstract and general among the three. The purpose of the abstract factory pattern is to provide an interface to the client to create product objects in multiple product families. Moreover, 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 of the products at a time.
2. Use products belonging to the same product family.
Let’s take a look at the various roles of the abstract factory pattern (as exactly the same as the factory method):
Abstract Factory Role: This is the core of the factory method pattern, it has nothing to do with the application. It is an interface that a specific factory role must implement or a parent class that must be inherited. In java it is implemented by abstract classes or interfaces.
Specific factory role: It contains code related to specific business logic. Called by the application to create the corresponding specific product object. In java it is implemented by concrete classes.
Abstract product role: It is the parent class or implementation interface of the specific product inheritance. In Java, there are generally abstract classes or interfaces to implement them.
Specific product role: The object created by a specific factory role is an instance of this role. Implemented by concrete classes in Java.
After reading the first two modes, I should have a clear idea of the coordination between the various characters in this mode, so I won’t give specific examples. It’s just that you must pay attention to meeting the conditions for using the abstract factory model, otherwise even if there are multiple product trees, there are still product families, but they cannot be used.
The above article has a deep understanding of the three factory models of Java. This is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.