Java Factory mode

Source: Internet
Author: User

Java Factory mode to see so much about the factory model of the explanation, or think this article is good understanding, paste out and share with you.
First, the primer
Ten years ago, there was a * * * household, his family has three cars--benz Mercedes-Benz, BMW BMW, Audi Audi, also hired a driver to drive for him. Just, * * * * * * is always a strange ride: on the Benz car and the driver said, "Drive Mercedes!" "When he was in BMW, he said," Drive a BMW! "Take the Audi and say," Drive the car! ”。 You must say: this man is sick! Just say you can't drive?!
When we put this behavior into our program design, we find that this is a ubiquitous phenomenon. Fortunately, such an illness can be avoided in OO (object-oriented) languages. The following is a Java language-based approach to the topic of our article: Factory mode.

Second, classification
The factory model provides a transition interface for creating objects to isolate the detailed process masking for creating objects for increased flexibility.

The factory model is divided into three categories in Java and mode:
1) Simple Factory mode (easy Factory)

2) Factory mode (Factory method)

3) Abstract Factory mode (Factory)
These three patterns are progressively abstracted from top to bottom and more general.
In design mode, GOF divides the factory model into two categories: The Factory method Mode (FactoryMethod) and the Abstract Factory mode (abstraction Factory). The Simple factory model (Simplefactory) is seen as a special case of the factory method pattern, which is grouped into one category.

Both can be used in this article using the "Java and Patterns" classification method. Take a look at how these factory models are "healing".

three, simple Factory mode

The simple factory model is also called the Static factory method mode. Renaming can see that this pattern must be very easy. The purpose of its existence is very easy: Define an interface for creating objects.
Let's take a look at its composition:

1) Factory class role: This is the core of this model, which contains certain business logic and inference logic. In Java it is often implemented by a detailed class.

2) Abstract Product role: it is usually the parent class for detailed product inheritance or an implemented interface. Implemented in Java by an interface or an abstract class.

3) Detailed Product role: the object created by the factory class is an instance of this role. Implemented in Java by a detailed class.
So how does the simple factory model work? We are simply using a simple factory model to transform the way a car is driven--now the user just needs to sit in the car and say to the driver, "drive".

Code:Abstract Product Roles
public interface car{
public void Drive ();
}

Detailed Product Roles
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 Roles
public class driver{
Factory method. Note The return type is abstract product role
public static Car Drivercar (String s) throws exception{
Inference logic, returning a detailed 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 appearance of the user ...
public class magnate{
public static void Main (string[] args) {
try{
Tell the driver I'm riding today.
Car car = Driver.drivercar ("Benz");
Next command: Drive
Car.drive ();
。。。


Fill out any other information that is vacant in this program and you can do so. If you put all the classes in a file, don't forget that only one class can be declared public. This procedure is carried out under jdk1.4.
This is the simple factory model. How easy is it to use? So what advantages does it bring?
First, after using the simple factory model, our program is not "sick", more in line with the reality of the situation, and the client is exempt from the direct creation of product objects, but only responsible for "consumption" products (as the * * * *).

Below we analyze the Simple Factory mode from the opening and closing principle (open for expansion; closing the change). When the user adds a car, only to conform to the abstract product contract, then only to inform the factory class know to be able to be used by customers. So for the part of the product, it is in line with the principle of open and closed, but the factory part seems to be not ideal, because each add a car, to add the corresponding business logic or inference logic in the factory class, which is obviously against the opening and shutting principle. We can imagine the addition of new products, factory class is very passive. For this factory class (which in our case is the driver's master), we call it the Almighty or the God class.
Our example is the simplest case, and in practical applications it is very likely that the product is a multi-layered tree structure. Because the simple factory model only has one factory class to correspond to these products, so this may put our God very tired and very tired of US these program apes: (
So the factory method model as Savior appeared.
four, factory method mode
The factory method pattern removes the static property of the factory method in the simple Factory mode, allowing it to inherit from the quilt class. The pressure to concentrate on factory methods in a simple factory model can be shared by different factory subclasses in the factory method model.

You should have roughly guessed the structure of the factory method pattern and look at its composition:

1) Abstract Factory role: This is the core of the factory method pattern, which is independent of the application. is the interface that the detailed factory role must implement or the parent class that must inherit. In Java it is implemented by an abstract class or interface.

2) Detailed factory role: it contains code related to detailed business logic. Called by the application to create the appropriate detailed product for the object.

3) Abstract Product role: It is the parent of detailed product inheritance or an interface implemented. In Java, there are generally abstract classes or interfaces to implement.

4) Detailed Product role: the object created by the detailed factory role is an instance of this role. Implemented in Java by a detailed class.
The factory method pattern uses multiple subclasses that inherit from the abstract factory role to replace the "God Class" in the simple factory pattern. As mentioned above, this shares the pressure of the object, and this makes the structure flexible-when a new product (ie, the car of the * * * * * * * *) is produced, it is only to be generated by the contract provided by the abstract product role and abstract factory role, then it can be used by the customer. Without having to change whatever code is already there. Can see the structure of the factory role is also in line with the principle of open and close!

We still have the same routine, using a complete sample to see how the various roles in the factory model are coordinated. Saying * * * * The business is bigger, their car is more and more. This can be bitter the driver master, what car it must remember, maintenance, all must go through him to use! So * * * * User Sympathy He said: "Look at you with me for so many years, after you do not have so hard, I assign you a few staff, you just tube good they can!" As a result, the management of the factory method pattern arose. The code is as follows:

Code:
Abstract product roles, the detailed product roles are similar to the simple factory model, just become more complex, here slightly.
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 be related to the detailed product formation ...
* * * * Mr. HU
public class magnate{
public static void Main (string[] args) {
try{
Driver Driver = new Benzdriver ();
Car car = Driver.drivercar ();
Car.drive ();
}
......
}


Can see the increase in factory methods, so that the number of objects multiplied. When the product variety is many, there will be a large number of corresponding factory objects, which is not what we want. Due to the assumption that this cannot be avoided, it is possible to consider using the simple factory model combined with the factory method pattern to reduce the factory class: That is, the simple factory pattern is used for similar species (usually brothers in the leaves of the tree) in the product tree.

v. Summary

The factory method pattern seems to have been perfectly wrapped in the creation of objects, allowing only the interfaces provided by the abstract product role to be processed in the client program. Do we have to be in the code all over the factory? It doesn't have to be big. Perhaps you can consider using the factory method mode in the following situations:

1) When the client program does not need to know to use the object creation process.

2) There is a possibility that the object used by the client is changing, or it is not known which detailed object to use at all.

The simple Factory mode and factory method mode really avoids the code changes? No. In the simple factory model, the addition of new products changes the inference statements in the factory role, while in the factory method mode either the inference logic is left in the abstract factory role or the detailed factory role is written to die in the client program (as in the example above). And the change of the Product object creation condition is bound to cause the changes of the factory role.
In the face of this situation, the ingenious combination of the reflection mechanism and the configuration file of Java breaks the limits-a perfect manifestation of spring.
VI. Abstract Factory mode

First come to know what is the product family: in the different product hierarchy structure, the function of the product group of related products. Let us illustrate it graphically with a sample.
Back to the topic of abstract Factory mode.
To be able to say, the difference between the abstract factory pattern and the factory method pattern is the complexity of the objects that need to be created. and the abstract factory model is the most abstract and most general of the three.
Abstract Factory mode is intended to provide the client with an interface to create product objects in multiple product families

Also, use the abstract Factory mode to meet the criteria:
1) There are multiple product families in the system, and the system may only consume one family of products at a time.
2) products belonging to the same product family for their use.
Take a look at the various roles of the abstract Factory model (as in the factory approach):
1) Abstract Factory role: This is the core of the factory method pattern, which is independent of the application. is the interface that the detailed factory role must implement or the parent class that must inherit. In Java it is implemented by an abstract class or interface.

2) Detailed factory role: it contains code related to detailed business logic. Called by the application to create the appropriate detailed product for the object. In Java it is implemented by a detailed class.

3) Abstract Product role: It is the parent of detailed product inheritance or an interface implemented. In Java, there are generally abstract classes or interfaces to implement.

4) Detailed Product role: the object created by the detailed factory role is an instance of this role. Implemented in Java by a detailed class.
I have seen the first two patterns, the coordination between the various roles of this pattern should have a number of hearts, I do not give detailed examples. Just be sure to pay attention to the conditions that use the abstract factory model. <script type= "Text/javascript" >&lt;! --google_ad_client = &quot;pub-4348265167276910&quot;;/ * 468x60, personal blog */google_ad_slot = &quot;2046406163&quot;; Google_ad_width = 468;google_ad_height = 60;//--&gt;</script><script src= "/http/ Pagead2.googlesyndication.com/pagead/show_ads.js "type=" Text/javascript "></script><script src=" http ://pagead2.googlesyndication.com/pagead/expansion_embed.js "></script><script src="/http Googleads.g.doubleclick.net/pagead/test_domain.js "></script><script>google_protectandrun (& Quot;ads_core.google_render_ad&quot, Google_handleerror, Google_render_ad);</script>

Java Factory mode

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.