Java Design Pattern Factory mode (Factory mode) Introduction _java

Source: Internet
Author: User
Tags getmessage

Factory Pattern Definition: Provides an interface for creating objects.

Why Use Factory mode

The factory pattern is our most commonly used pattern, the famous Jive Forum, has used the factory pattern extensively, the factory pattern in the Java program system can say is everywhere.

Why is the factory model so common? Because the factory pattern is the equivalent of creating a new instance object, we often have to generate instance objects based on class classes, such as a a=new a () factory pattern is also used to create instance objects, so there will be more than one mind at a later time, whether it is possible to consider a practical factory model, although doing so may do more work But it will bring greater scalability and minimal modification to your system.

Let's take class sample for example, if we want to create an instance object for sample:

Copy Code code as follows:

Sample Sample=new sample ();

However, the reality is that we usually do some initialization work when we create sample instances, such as assignment query database.

First, we think that you can use the constructor of sample, so that the instance is written:

Copy Code code as follows:

Sample Sample=new sample (parameter);

However, if you are creating an instance of sample with an initialization that is not as simple as an assignment, it may be a long piece of code, and if you write to the constructor, your code is very difficult to read (you need to refactor the reorganization).

Why is it so hard to see the code, beginners may not feel this way, we analyze the following, initialization work if it is a long piece of code to do a lot of work, put a lot of work in a method, the equivalent of putting a lot of eggs in a basket, is very dangerous, this is also a back to the Java object-oriented principle, Object-oriented encapsulation (encapsulation) and dispatch (delegation) tell us, try to assign the long code "cut" into each segment, and then "encapsulate" each paragraph (reduce the coupling between segments and segments), so that the risk will be dispersed, if you need to modify, as long as you change each paragraph , will not happen to pull a move hundred things.

In this case, first of all, we need to separate the creation of the instance from the work using the instance, that is, to let the bulk of the initialization that is required to create the instance separate from the constructor of sample.

Then we need to factory Factory mode to generate objects, can no longer use the above simple new Sample (parameters). Also, if sample has an inheritance such as mysample, we need to abstract sample into an interface, as directed to interface programming. Now sample is an interface with two subclasses of Mysample and Hissample. We want to instantiate them when the following:

Copy Code code as follows:

Sample mysample=new mysample (); Sample hissample=new hissample ();

As the project progresses, sample may also "give birth to a lot of sons", so we have to instantiate each of these sons, and, worse, perhaps modify the previous code: Join the example of a later birth of a son. This is unavoidable in traditional programs.

But if you start out with the idea of using the factory model, the trouble is gone.

Factory method

You will build a factory specializing in the production of sample samples:

Copy Code code as follows:

public class factory{
public static Sample creator (int which) {
GetClass generate a sample you can typically load a class with a dynamic class.
if (which==1)
return new Samplea ();
else if (which==2)
return new Sampleb ();
}
}

So in your program, if you want to instantiate sample, use the

Copy Code code as follows:

Sample Samplea=factory.creator (1);

In this way, the whole does not involve the specific subclass of sample, to achieve the package effect, but also to reduce the chance of error modification, this principle can be used in a very popular words to analogy: is the specific things to do more, the more easily fan error. Each person who has done a specific job has a deep experience, on the contrary, the higher the official does, the more abstract the words are, the less likely the error is. As if we can realize the truth of life from the process of coding?

The use of factory methods to pay attention to several roles, first of all, you have to define the product interface, such as the above sample, the product interface has a sample interface implementation class, such as Samplea, followed by a factory class, to generate product sample, the following figure, On the far right is the object of production sample:


Further slightly more complex, is to expand in the factory class, the factory class also has inherited its implementation class concretefactory.

Abstract Factory
factory models include: Factory Methods (Factory method) and abstract factories (Abstracts Factory).

The difference between the two modes is the degree to which the object needs to be created. If the way we create objects becomes complicated, as the factory method above is to create an object named sample, if we have a new product interface Sample2.

This assumes that: sample has two concrete class Samplea and Samleb, and Sample2 also has two concrete classes SAMPLE2A and SampleB2, then we will factory in the above example into an abstract class, The common part is encapsulated in an abstract class, and the different parts are implemented using subclasses, and the following is to expand the factory in the example above into an abstract factory:

Copy Code code as follows:

Public abstract class factory{
Public abstract Sample creator ();
Public abstract Sample2 Creator (String name);
}
public class Simplefactory extends factory{
Public Sample Creator () {... return new Samplea}
Public Sample2 Creator (String name) {... return new SAMPLE2A}
}
public class Bombfactory extends factory{
Public Sample Creator () {... return new Sampleb}
Public Sample2 Creator (String name) {... return new sample2b}
}

From the above see two factories each produce a set of sample and Sample2, perhaps you will doubt, why I can not use two factory methods to produce sample and Sample2 separately?

Another key point in the abstract factory is that there is a connection between the methods of producing sample and producing Sample2 in Simplefactory, so that the two methods are bundled in a class, which has its own characteristics, and perhaps the manufacturing process is uniform, For example: The manufacturing process is relatively simple, so the name is called Simplefactory.

In practical application, the factory method is used more, and it is combined with the dynamic class loader,

Examples of Java factory patterns

Let's take Jive's forumfactory as an example, which we discussed in the previous singleton model and now discuss its factory model:

Copy Code code as follows:

Public abstract class Forumfactory {
private static Object Initlock = new Object (); private static String ClassName = "Com.jivesoftware.forum.database.DbForumFactory"; private static forumfactory factory = null;
public static Forumfactory getinstance (Authorization Authorization) {
IF no valid authorization passed in, return null.
if (authorization = = NULL) {return null;}
The following uses the singleton single State mode
if (factory = = null) {
Synchronized (Initlock) {
if (factory = = null) {...
try {
Dynamic Reprint Class
Class C = class.forname (ClassName);
Factory = (forumfactory) c.newinstance ();
catch (Exception e) {return null;}
}
}
}
Now, return proxy. Used to restrict authorization to forum access
return new Forumfactoryproxy (authorization, factory,factory.getpermissions (authorization));
}
The method that really creates the forum is done by inheriting the Forumfactory subclass.
Public abstract Forum Createforum (string name, string description)
Throws Unauthorizedexception, Forumalreadyexistsexception;
....
}

Because the current jive is through the database system to store forum posts and other content data, if you want to change to achieve through the file system, this factory method Forumfactory provides a dynamic interface:

Copy Code code as follows:

private static String ClassName = "Com.jivesoftware.forum.database.DbForumFactory";

You can use the method you developed to create forum instead of com.jivesoftware.forum.database.DbForumFactory.

In the above section of the code in a total of three modes, in addition to Factory mode, there are singleton mode, as well as proxy mode, proxy mode is mainly used to authorize users to forum access, because access to forum there are two types of people: one is a registered user is a visitor guest, Then the corresponding permissions are not the same, and this permission is throughout the system, so the establishment of a proxy, similar to the concept of a gateway, can be very good to achieve this effect.

Look at the catalogdaofactory in the Java Pet store:

Copy Code code as follows:

public class Catalogdaofactory {
/**
* This method developed a special subclass to implement the DAO pattern.
* The specific subclass definition is in the Java EE deployment Descriptor.
*/
public static Catalogdao Getdao () throws catalogdaosysexception{
Catalogdao Catdao = null;
try {
InitialContext IC = new InitialContext ();
Dynamic Loading Catalog_dao_class
You can define your own catalog_dao_class so that you don't have to change too much code
Under the premise of the system to complete the huge changes.
String className = (string) ic.lookup (Jndinames.catalog_dao_class);
Catdao = (Catalogdao) class.forname (className). newinstance ();
catch (Namingexception ne) {
throw new Catalogdaosysexception ("CatalogDAOFactory.getDAO:NamingException while getting DAO type: \ n" + ne.getmessage ( ));
catch (Exception se) {
throw new Catalogdaosysexception ("CatalogDAOFactory.getDAO:Exception while getting DAO type: \ n" + se.getmessage ());
}
return Catdao;
}
}

Catalogdaofactory is a typical factory approach, Catdao is a dynamic class loader classname to obtain catalogdaofactory specific implementation subclass, this implementation subclass in the Java Pet Store is used to manipulate the catalog database, Depending on the type of database, users can customize their own specific implementation subclasses, and give their subclass names to catalog_dao_class variables.

This shows that the factory method does provide a very flexible and powerful dynamic extension mechanism for the system structure, as long as we change the specific factory method, the other place of the system without a little transformation, it is possible to change the function of the system.

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.