Introduction to the Factory mode (Factory mode) of Java design mode (reprint)

Source: Internet
Author: User

See the original: http://www.jb51.net/article/62068.htm

This article mainly introduces the Java design mode of the factory model (Factory mode) Introduction, this article explains why the use of Factory mode, factory methods, abstract factory, Java factory model examples, such as the needs of friends can refer to the following

Factory mode definition: Provides an interface for creating objects.

Why Use Factory mode

Factory mode is our most commonly used mode, the famous Jive Forum, on the use of a lot of Factory mode, Factory mode in Java program system can be said to be ubiquitous.

Why is Factory mode so often used? Because the factory pattern is equivalent to creating the instance object's new, we often have to build the instance object according to class classes, such as the A A=new a () factory pattern is also used to create instance objects, so later new will be more than the mind, whether you can consider the practical Factory mode, although doing so, may do more work, But it will give you greater scalability and minimal modification.

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

Copy CodeThe code is as follows:
Sample Sample=new sample ();
However, the reality is that we usually do some initialization work when we create the sample instance, such as the assignment query database.

First, the idea is that you can use the constructor of sample so that the generated instance is written as:

Copy CodeThe code is as follows:
Sample Sample=new sample (parameter);
However, if the initialization that you do when you create a sample instance is not as simple as assigning a value, it can be a long code, and if you write to the constructor, your code is hard to read (you need to refactor the reorganization).

Why the code is difficult to see, beginners may not feel this, we analyze the following, the initialization of the work if it is a long code, to do a lot of work, put a lot of work into a method, the equivalent of putting a lot of eggs in a basket, it is very dangerous, it is back to the Java object-oriented principle, Object-oriented encapsulation (encapsulation) and dispatch (delegation) tell us to try to assign long code "cut" to each segment, and then "encapsulate" each segment (reducing the coupling between segments and segments) so that risk is dispersed and, if necessary, changed at a later time, as long as each , will not happen to take a move hundred things.

In this case, first, we need to separate the work of creating an instance from the work of using an instance, which means that the amount of initialization required to create an instance is separated from the constructor of sample.

At this point we need to factory the Factory mode to generate the object, can not use the above simple new Sample (parameter). Also, if sample has an inheritance such as mysample, we need to abstract the sample into an interface in terms of interface-oriented programming. Now sample is an interface, there are two subclasses of Mysample and Hissample. When we want to instantiate them, here are the following:

Copy CodeThe code is 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'll instantiate these sons, and, worse, make changes to the previous code: Adding an instance of the son later. This is unavoidable in traditional programs.

But if you've been conscious of using the factory model from the start, the trouble is gone.

Factory method

You will create a factory that specializes in producing sample instances:

Copy CodeThe code is as follows:
public class factory{
public static Sample creator (int which) {
GetClass Generation sample You can typically use dynamic classes to load a load class.
if (which==1)
return new Samplea ();
else if (which==2)
return new Sampleb ();
}
}

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

Copy CodeThe code is 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 analogy: the more specific things to do, the more prone to error. Each person who has done specific work has deep experience, on the contrary, the higher the official to do, the more abstract the more general, the less likely the likelihood of error. As if we can realize the truth of life in the process of compiling?

Use factory method to pay attention to several roles, first you have to define the product interface, such as the above sample, the product interface has the sample interface implementation class, such as Samplea, followed by a factory class, used to generate product sample, such as, the rightmost is the production of the object sample:


A little bit more complicated, that is, in the factory class to expand, the factory class has inherited its implementation class concretefactory.

Abstract Factory
In the factory model are: Factory methods (Factory method) and abstract Factory.

The difference between the two patterns is the complexity of the objects that need to be created. If our method of creating an object becomes complicated, as the above factory method is to create an object sample, if we have a new product interface Sample2.

Here's a hypothesis: sample has two concrete classes Samplea and Samleb, and Sample2 has two concrete classes SAMPLE2A and SampleB2, so we'll turn factory into abstract class in the example above, The common part is encapsulated in an abstract class, the different parts are implemented using subclasses, and the following is the extension of the factory in the example above into an abstract factory:

Copy CodeThe code is 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 to see two factories each produced a set of sample and Sample2, perhaps you will wonder, why I can not use two factory methods to separate the production of sample and Sample2?

There is another key point in the abstract factory, because there is a connection between the production of sample and the method of producing Sample2 in Simplefactory, so the two methods must be bundled in a class, the factory class has its own characteristics, perhaps the manufacturing process is unified, For example: The manufacturing process is relatively simple, so the name is called Simplefactory.

In practical applications, factory methods are used more, and are combined with dynamic class loader to apply,

Java Factory Model Example

We take Jive's forumfactory as an example, as we discussed in the previous singleton model, and now we discuss its Factory mode:

Copy CodeThe code is 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 to proxy. To restrict access to the forum for authorization
return new Forumfactoryproxy (authorization, factory,factory.getpermissions (authorization));
}
The way to really create a forum is done by inheriting forumfactory subclasses.
Public abstract Forum Createforum (string name, string description)
Throws Unauthorizedexception, Forumalreadyexistsexception;
....
}

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

Copy CodeThe code is as follows:
private static String ClassName = "Com.jivesoftware.forum.database.DbForumFactory";
You can use your own developed forum method instead of com.jivesoftware.forum.database.DbForumFactory.

In a total of three modes in the above code, in addition to the Factory mode, there are singleton single mode, as well as proxy mode, the proxy mode is mainly used to authorize the user access to the forum, because there are two types of Access forum: 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 gateway, can be very good to achieve this effect.

Check out the catalogdaofactory in the Java Pet store:

Copy CodeThe code is as follows:
public class Catalogdaofactory {
/**
* This method formulates a special subclass to implement the DAO pattern.
* The specific subclass definition is in the deployment descriptor of the Java EE.
*/
public static Catalogdao Getdao () throws catalogdaosysexception{
Catalogdao Catdao = null;
try {
InitialContext IC = new InitialContext ();
Dynamically loading Catalog_dao_class
You can define your own catalog_dao_class, so you don't have to change too much code
, the system changes dramatically.
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 method, Catdao is to obtain catalogdaofactory concrete implementation subclass through the dynamic class loader classname, this implementation subclass is used in the Java pet store to manipulate the catalog database, Depending on the type of database, users can customize their own implementation subclasses, and give their subclass names to catalog_dao_class variables.

Thus, the factory method does provide a very flexible and powerful dynamic expansion mechanism for the system structure, so long as we change the specific factory method, the system can change the function of the system without a little change anywhere else.

Introduction to the Factory mode (Factory mode) of Java design mode (reprint)

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.