Deep understanding of Java three factory patterns _java

Source: Internet
Author: User

Applicable occasions:

7.3 Application of Factory mode

The easiest way to create a new object is to use the New keyword and the specific class. The extra complexity of creating and maintaining object factories is worth it only in some cases. These occasions are summarized in this section.

7.3.1 Dynamic Implementation

If you need to create objects that implement the same interface in different ways, as in the case of the previous bike, you can use a factory method or simple factory object to simplify the process of selecting implementations. This choice can be either explicit or implied. The former example of a bicycle, customers can choose the type of bicycle, and the next section of the XHR factory that example is the latter, the type of connection object returned in this example depends on the detected bandwidth and network latency 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 mode in JavaScript.

7.3.2 Save Setup Overhead

If objects require complex and interrelated settings, the use of Factory mode can reduce the amount of code required for each type of object. This is especially true if this setting only needs to be performed once for all instances of a particular type. It is not an efficient practice to put this setup code into the constructor of a class, because even if the setup work is done, the code will execute each time a new instance is created, and this will spread the setup code into different classes. The factory method is very suitable for this occasion. It can be set once before instantiating all the objects that are needed. Regardless of how many different classes are instantiated, this approach allows the set code to be concentrated in one place.

This is especially useful if you are using a class that requires an external library to be loaded. The factory method can check these libraries and dynamically load those libraries that are not found. These settings codes exist only in one place, so it is much easier to change them later.

7.3.3 a large object with many small objects

Factory methods can be used to create objects that encapsulate many smaller objects. Consider the constructor of the bike object. Bicycles contain many smaller subsystems: wheels, frames, drive parts, and brakes. The factory approach is an ideal choice if you don't want a subsystem to be strongly coupled to a larger object, but rather to pick from many subsystems at run time. With this technique, one day you can have a chain for all the bikes you sell, and if you find another more desirable chain the next day, you can change the new breed. It is easy to make this change because the constructors of these bikes do not depend on a particular chain breed. An example of an RSS reader later in this chapter demonstrates the use of the factory pattern in this regard.

The factory pattern primarily provides an interface for creating objects. The factory model is divided into three categories according to the references in Java and schema:

1. Simple factory model (easy Factory)

2. Factory mode (Factory method)

3. Abstract Factory Model (abstracts Factory)

These three patterns are progressively abstracted from top to bottom and more general. There is also a classification method, which is to see the simple factory model as a special case of the factory method pattern, and two are classified as a class. Here are two things that use the factory pattern:

1. It is not possible to foresee what kind of instance to create when coding.

2. Systems should not rely on the details of how product class instances are created, assembled, and expressed

Three, simple Factory mode

As the name suggests, this pattern is simple in itself and is used in simpler business situations.

It consists of three different roles (see the class diagram below):

1, the factory class role: This is the core of this model, contains a certain business logic and judgment logic. In Java it is often implemented by a specific class.

2, the abstract product role: it is generally a specific product inherited by the parent class or the implementation of the interface. Implemented in Java by an interface or abstract class.

3. Specific product role: the object created by the factory class is an instance of this role. Implemented in Java by a specific class.

So how does a simple factory model work? Let me give you an example, I think this is much easier to understand than a large paragraph of theoretical text description! Here's to give the upstart The Cure: P

After using the simple factory model, now the nouveau riche just need to sit in the car and say to the driver: "Drive" is OK. Let's see how it's accomplished:

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"); 
。。 (Audi I will not write: P) 
//factory class Role Public 
class driver{// 
factory method 
//Note return type is abstract product role public 
static car Drivercar (String s) throws Exception { 
//judgment logic, returning specific product roles to client 
if (s.equalsignorecase ("Benz")) return new Benz (); 
else if (s.equalsignorecase ("BMW")) return to 
new BMW (); 
...... 
else throw new Exception (); 
//Welcome nouveau riche Appearance 
... public class magnate{public 
static void Main (string[] args) { 
try{ 
//Tell the driver I'm taking the Mercedes car today. 
Driver.drivercar ("Benz"); 
Next command: Drive 
car.drive (); 

If you put all your classes in one file, remember that only one class is declared public. The relationships between classes in a program are as follows:

This is the simple factory model. Here are the benefits:

First of all, with the simple factory model, our program is not "sick", more in line with the real situation, and the client is exempt from the direct creation of the product object, but simply responsible for "consumer" products (as the nouveau riche).

Below we will analyze the simple Factory mode from the open and closed principle. When the nouveau riche added a car, as long as the contract to meet the abstract products, so long as the notification factory class know can be used by customers. So for the product part, it is in line with the opening and closing principles-open to expansion, to the modification of the closure; but the factory part seems to be not ideal, because each additional car, should be in the factory class to add the corresponding business logic and judgment logic, which obviously violates the opening and closing principle.

For such a factory class (in our case for the driver), we call it an almighty class or a God class.

The example we cite is the simplest case, and in practice it is likely that the product is a multi-level, tree-like structure. Because there is only one factory class in the simple factory model that corresponds to these products, it may be bad for our God class, and then we'll be tired of our lovely programmers: (

As I mentioned earlier the simple factory model applies to the case where the business will be simple. The complex business environment may not be very adaptable. This should be the factory method mode to come out!!

Four, the factory method mode

Let's take a look at its composition:

1, Abstract Factory role: This is the core of the factory method pattern, it is not related to the application. is the interface that the specific factory role must implement or the parent class that must be inherited. In Java, it is implemented by an abstract class or interface.

2, the specific factory role: it contains the specific business logic related to the code. An object that is called by the application to create the corresponding specific product. In Java it is implemented by a specific class.

3, abstract product role: It is the specific product of the parent class or the implementation of the interface. Abstract classes or interfaces are generally implemented in Java.

4. Specific product role: the object created by the specific factory role is an instance of this role. Implemented in Java by a specific class.

To use the class diagram to clearly represent the relationships between them:

Let's use a complete example to see how the various roles in the factory model are coordinated. In other words, nouveau riche business more and more, their own car is more and more. This can be bitter that driver master, what car it must remember, maintenance, must pass him to use! So the nouveau riche sympathized with him and said, "Look at you and me for so many years, after you don't have to work so hard, I give you a few hands, you just manage them on the line!" As a result, the management of the factory method pattern appeared. The code is as follows:

Abstract product roles, specific product roles similar to the simple factory model, are just getting a little more complicated here. 
//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 (); 
} 
.../should have a corresponding relationship with the specific products, here slightly ... 
Mr. Nouveau riche. 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 approach uses an abstract factory role as the core instead of using specific classes as the core in the simple factory pattern. Let's look at what the factory method model brings to us. Use the open and closed principle to analyze the factory method model. When new products (i.e., nouveau riche cars) are produced, they can be used by customers without modifying any existing code, as long as they are generated by the contracts provided by the abstract product role and abstract factory role. It seems that the factory method model is completely in line with the opening and closing principle!

Using the factory method pattern is sufficient to meet most of the business requirements that we may encounter. But when the product range is very large, there will be a lot of corresponding factory class, this should not be what we want. So I would suggest that in this case the factory class should be reduced by combining the simple factory model with the factory method pattern: That is, the simple factory pattern is used for similar types in the product tree (usually siblings in the leaves of the tree).

Of course, special treatment is necessary: there are different product trees in the system, and the product family exists in the product tree, then the abstract factory pattern may be used in this case.

V. Summary

Let's take a look at the simple factory model, the factory method model to enlighten us:

If you do not use Factory mode to implement our example, perhaps the code will be reduced a lot-only to implement the existing car, do not use polymorphism. But on maintainability, scalability is very poor (you can imagine a class to be affected by adding a car). So in order to improve extensibility and maintainability, it is worthwhile to write more code.

VI. Abstract Factory model

First come to know what the product family is: a family of products that are in different product hierarchy and have a function associated with it. I have to admire you if you can clearly understand this concept by reading this sentence. Let's use an example to illustrate it.

The Bmwcar and Benzcar in the figure are two product trees (product hierarchies), and Benzsportscar and Bmwsportscar, as shown in the figure, are a product family. They can all be put into the sports car family, so the function is related. Similarly Bmwbussinesscar and Benzsportscar are also a product family.

Back to the topic of abstract product patterns, it can be said that it differs from the factory method pattern in the complexity of the objects that need to be created. and the abstract factory model is one of the three most abstract and general. Abstract Factory mode is intended to provide an interface to clients that can create product objects in multiple product families. and use the abstract factory pattern to meet the conditions:

1. There are multiple product families in the system, and the system may only consume one of the products at a time.

2. Use of products belonging to the same product family.

Take a look at the various roles of the abstract Factory pattern (as in the factory approach):

Abstract Factory Role: This is the core of the factory method pattern, and it has nothing to do with the application. is the interface that the specific factory role must implement or the parent class that must be inherited. In Java, it is implemented by an abstract class or interface.

Specific factory role: It contains code related to specific business logic. An object that is called by the application to create the corresponding specific product. In Java it is implemented by a specific class.

Abstract Product Role: It is the parent class or implementation interface for a specific product. Abstract classes or interfaces are generally implemented in Java.

specific product role: The object created by the specific factory role is an instance of this role. Implemented in Java by a specific class.

After looking at the first two modes, there should be a number of coordination between the roles in this pattern, and I will not give a specific example. Just be sure to pay attention to the use of abstract factory model conditions Oh, otherwise, even if there are multiple product trees, there are product families, but can not use the

The above in-depth understanding of the Java three factory model is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

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.