Java three factory models, java three factory

Source: Internet
Author: User

Java three factory models, java three factory

Applicable scenarios:
7.3 applicable scenarios of the factory Model

The simplest way to create a new object is to use the new keyword and a specific class. Only in some cases, the extra complexity brought about by the creation and maintenance of the object factory is worth the money. This section summarizes these scenarios.

7.3.1 dynamic implementation

If you want to create objects that implement the same interface in different ways like in the previous example of a bicycle, you can use a factory method or a simple factory object to simplify the selection and implementation process. This kind of choice can be either explicit or implicit. The former is like a bicycle, and the customer can select the desired bicycle model. The XHR factory example in the next section belongs to the latter, the type of the connection object returned in this example depends on factors such as the bandwidth and network latency. In these cases, you usually have to deal with a series of classes that implement the same interface and can be treated similarly. This is the most common reason for using the factory mode in JavaScript.

7.3.2 saving configuration overhead

If the object requires complex and related settings, you can use the factory mode to reduce the amount of code required for each object. If this setting only needs to be executed once for all instances of a specific type, this is particularly important. Putting this setting code into the class constructor is not an efficient method. This is because the code will be executed every time a new instance is created even if the setting is completed, in addition, the Set code is distributed to different classes. The factory method is very suitable for this scenario. It can be set at one time before all required objects are instantiated. No matter how many different classes are instantiated, This method allows the set code to be concentrated in one place.

This is especially useful if the classes used require loading external libraries. Factory methods can check these libraries and dynamically load those unfound libraries. These setting codes only exist in one place, so it is much easier to change them later.

7.3.3 make up a large object with many small objects

The factory method can be used to create objects that encapsulate many small objects. Consider the bike object constructor. Bicycles contain many smaller subsystems: wheels, frames, transmission components, and brakes. If you do not want a subsystem to form a strong coupling with a large object, but want to select from many subsystems during runtime, the factory method is an ideal choice. Using this technology, you can match all the bicycles sold with a certain chain one day. If you find another kind of favorite chain the next day, you can change it to use this new product. It is easy to implement this change because the constructors of these bicycle classes do not depend on a specific chain type. The example of an RSS reader later in this chapter demonstrates the purpose of the factory model in this regard.


The factory mode provides interfaces for object creation. Factory models are classified into three types based on the concepts in Java and patterns:
1. Simple Factory)
2. Factory Method)
3. Abstract Factory)
These three models are gradually abstracted from top to bottom and more general. Another kind of classification is to look at the simple factory model as a special case of the factory method model. The two are classified as one type. The following two scenarios use the factory model:
1. You cannot predict the type of instance to be created during encoding.
2. The system should not rely on the details of how product instances are created, combined, and expressed.


3. Simple factory Model
As the name suggests, this mode is simple and easy to use when the business is relatively simple.
It consists of three roles (for the relationship, see the class diagram below ):
1. Factory roles: this is the core of this model and contains some commercial logic and judgment logic. In java, it is often implemented by a specific class.
2. Abstract Product role: it is generally the parent class or implemented interface inherited by a specific product. It is implemented by interfaces or abstract classes in java.
3. Specific product role: the object created by the factory class is the instance of this role. It is implemented by a specific class in java.
How can we use the simple factory model? Let me give you an example. I think this is much easier to understand than a large theoretical text description! Let's take care of the nouveau riche: P
After using the simple factory model, the nouveau riche now only needs to sit in the car and say "Driving" to the driver. 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 will not write about Audi: P)
// Factory role
Public class Driver {
// Factory Method
// Note that the return type is an abstract Product role.
Public static Car driverCar (String s) throws Exception {
// Judge the logic and return the specific product role to the Client
If (s. equalsIgnoreCase ("Benz") return new Benz ();
Else if (s. equalsIgnoreCase ("Bmw "))
Return new Bmw ();
......
Else throw new Exception ();
...
// Welcome to the startup ......
Public class Magnate {
Public static void main (String [] args ){
Try {
// Tell the driver that I am taking the Mercedes today
Car car = Driver. driverCar ("benz ");
// Run the following command: Drive
Car. drive ();
...
If you put all classes in one file, do not forget that only one class can be declared as public. The relationships between classes in the program are as follows:
This is a simple factory model. The following are the benefits:
First, after the simple factory mode is used, our program is not "abnormal" and is more in line with the actual situation. Besides, the client is not responsible for directly creating product objects, instead, it is only responsible for "consuming" Products (just as the act of a nouveau riche ).
Next we will analyze the simple factory mode from the principle of opening and closing. When a nouveau riche adds a car, as long as it complies with the contract of the abstract product, it can be used by the customer as long as the factory class is notified. For the product part, it is in line with the principle of opening and closing-open to expansion and closed to modification; but the factory part does not seem ideal, because every time a car is added, the 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 example it is a driver master), we call it an all-powerful class or a god class.
The example here is the simplest case. In practical applications, the product is probably a multi-layer tree structure. Since there is only one factory class in the simple factory model to correspond to these products, this may break down our God class, and then break down our lovely programmers :(
As I mentioned earlier, the simple factory model applies when the business will be simple. However, it may not be suitable for complicated business environments. This should be done in the factory method mode !!
Iv. Factory method mode
Let's take a look at its composition:
1. Abstract Factory role: this is the core of the factory method model and has nothing to do with applications. It is an interface that must be implemented by a specific factory role 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. An application is called to create the objects of a specific product. In java, it is implemented by a specific class.
3. Abstract Product role: it is the parent class or implemented interface inherited by a specific product. In java, abstract classes or interfaces are generally used for implementation.
4. Specific product role: the object created by the specific factory role is the instance of this role. It is implemented by specific classes in java.
To use a class chart to clearly express the relationship between them:
We still use the old rule to use a complete example to see how the roles in the factory model are coordinated. In other words, the larger the startup business, the more cars they love. It's hard for the driver's master to remember and maintain any car. He will use it! As a result, the nouveau riche sympathized with him and said, "You don't have to work so hard in the future. I will assign you several people. You just need to manage them! As a result, the management of the factory method model emerged. The Code is as follows:
// Abstract the product role. The specific product role is similar to the simple factory model, but it is more complicated.
// 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 have a corresponding relationship with a specific product...
// The attacker is welcome.
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 a specific class as the core in a simple factory model. Let's take a look at what the factory method model has brought to us? Use the open/closed principle to analyze the factory method mode. When a new product (that is, a nouveau riche car) is generated, it can be used by the customer as long as it is generated according to the contract provided by the abstract Product role and the abstract factory role, instead of modifying any existing code. It seems that the factory method mode is completely in line with the principle of opening and closing!
The factory approach is sufficient to meet most of the business needs we may encounter. However, when there are many product categories, there will be a large number of corresponding factory categories, which is not what we want. In this case, we recommend that you use the simple factory mode and factory method mode to reduce the factory class: that is to say, a simple factory model is used for similar types on the product tree (generally the leaves of the tree are sibling ones.
Of course, in special cases, we have to take special measures: There are different product trees in the system and there are product families in the product tree. In this case, we may be able to use the abstract factory model.
V. Summary
Let's take a look at the inspiration given by the simple factory model and factory method model:
If we do not use the factory mode to implement our example, the code may be much reduced-we only need to implement the existing car without using polymorphism. But in terms of maintainability, scalability is very poor (you can imagine the class to be affected after adding a car ). Therefore, it is worthwhile to write more code to improve scalability and maintainability.
Vi. Abstract Factory Model
First, let's take a look at what is a product family: A family of products with different product levels and functions. If you read this sentence, you can understand this concept clearly. I have to admire you. Let's illustrate it with an example.
BmwCar and BenzCar in the figure are two product trees (product hierarchy), while BenzSportsCar and BmwSportsCar are one product family. They can all be placed in the sports car family, so their functions are related. BmwBussinessCar and BenzSportsCar are also product families.
Back to the topic of the abstract product model, we can say that the difference between it and the factory method mode lies in the complexity of object creation. In addition, the abstract factory model is the most abstract and general among the three. Abstract Factory mode provides an interface for the client to create product objects in multiple product families. In addition, the abstract factory model must meet the following conditions:
1. There are multiple product families in the system, and the system can only consume one product family at a time.
2. products belonging to the same product family are used by them.
Let's take a look at the roles of the abstract factory model (similar to the factory method ):
Abstract Factory role: this is the core of the factory method model and has nothing to do with the application. It is an interface that must be implemented by a specific factory role 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. An application is called to create the objects of a specific product. In java, it is implemented by a specific class.
Abstract Product role: it is the parent class or implemented interface inherited by a specific product. In java, abstract classes or interfaces are generally used for implementation.
Specific product role: the object created by the specific factory role is the instance of this role. It is implemented by specific classes in java.
After reading the first two models, I should be aware of the number of roles in this model. I will not give a specific example. But be sure to meet the conditions for using the abstract factory model. Otherwise, even if there are multiple product trees, there are product families, but they cannot be used.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.