Factory1 of design pattern (comparison of simple factory, factory method and abstract factory)

Source: Internet
Author: User

Banqiao people http://www.jdon.com 2002/10/07 (reproduced please keep)

Practical Mode books Java Practical System Development Guide

Factory mode definition: Provides interfaces for object creation.

Why?
The factory mode is our most commonly used model. The famous jive forum has used the factory mode extensively. The factory mode can be seen everywhere in Java program systems.

Why is the factory model so commonly used? Because the factory mode is equivalent to creating the new instance object, we often need to generate instance objects according to class, for example, a A = new A () Factory mode is also used to create instance objects, so in the future, there will be multiple eyes. Can you consider the practical factory model? Although doing so may do more work, it will bring more scalability and as few modifications as possible to your system.

Let's take the sample class as an example. If we want to create an instance object for the sample:

Sample sample = new sample ();

However, we usually perform vertex initialization when creating a sample instance, such as assigning values to query databases.

First, we can use the sample constructor to generate an instance and write it as follows:

Sample sample = new sample (parameter );

However, if Initialization is not as simple as assigning values when creating a sample instance, it may be a long piece of code. If it is also written to the constructor, then your code is ugly (refactor reorganization is required ).

The reason is that the Code is ugly. Beginners may not feel this way. We will analyze the following. If the initialization work is a long piece of code, it means a lot of work to be done and a lot of work is loaded into a method, it is very dangerous to put a lot of eggs in one basket. This is also based on Java's object-oriented principle. The object-oriented encapsulation (encapsulation) and dispatch (Delegation) tell us that, assign long codes as much as possible to "cut" each segment, and then "encapsulate" each segment (reducing the coupling and association between segments). In this way, risks are dispersed, if you need to modify each segment in the future, nothing will happen again.

In this example, we need to separate the instance creation and use, that is, separate the large amount of initialization work required to create an instance from the constructor of the sample.

In this case, we need the factory mode to generate the object, and we cannot use the simple new sample (parameter) above ). In addition, if the sample has an inheritance such as mysample, We need to abstract the sample into an interface according to the interface-oriented programming. sample is an interface with two subclasses: mysample and hissample. we want to instantiate them as follows:

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

As the project goes deeper, the sample may "give birth to many sons", so we need to instantiate these sons one by one. Even worse, we may need to modify the previous Code: add an instance that later gave birth to a son. this is unavoidable in traditional programs.

But if you consciously use the factory model from the very beginning, these troubles will be gone.

Factory method
You will create a factory dedicated to producing sample instances:

Public class factory {

Public static sample creator (INT which ){

// Getclass generates samples. Generally, dynamic classes can be used to load the loaded classes.
If (which = 1)
Return new samplea ();
Else if (which = 2)
Return new sampleb ();

}

}

In your program, if you want to instantiate the sample, use

Sample samplea = factory. creator (1 );

In this way, the entire process does not involve the specific sub-classes of the sample to achieve the encapsulation effect, which reduces the chance of Error modification. This principle can be expressed in a very popular way: the more specific things are done, the easier it is to set errors. each person who has done a specific job has a deep understanding. On the contrary, the higher the officer is, the more abstract the words are, the less likely the fan errors will be. it seems that we can understand the truth of life from the programming? Haha.

To use the factory method, pay attention to several roles. First, you must define the product interface. The sample interface implementation class, such as samplea, must be included in the product interface, used to generate the product sample. For example, the rightmost is the production object sample:

A little more complicated, that is, to expand the factory class, the factory class also inherits its implementation class concretefactory..

Abstract Factory
Factory Methods abstract factory ).

The difference between the two modes lies in the complexity of creating objects. If the method for creating an object becomes complicated, for example, the factory method above creates an object sample. If we still have a new product interface sample2.

Assume that sample has two concrete classes samplea and samleb, and sample2 has two concrete classes sample2a and sampleb2.

In this case, the factory in the above example is converted into an abstract class, and the common part is encapsulated in the abstract class. Different parts are implemented using subclasses. below, the factory in the above example is extended to an abstract factory:

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
}

}

 

We can see from the above that two factories each produce a set of sample and sample2. Maybe you may wonder, why can't I use two factory methods to produce sample and sample2 separately?

Another key point of the abstract factory is that there is a certain relationship between the methods for producing sample and sample2 in simplefactory, so we need to bind these two methods to a class, this factory class has its own characteristics, maybe the manufacturing process is unified, for example: the manufacturing process is relatively simple, so the name is simplefactory.

In practical applications, the factory method is used more often and combined with the dynamic class loader,

Example

Let's take jive's forumfactory as an example. This example is discussed in the previous Singleton mode. Now we will discuss its factory mode:

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 ){
// If no valid authorization passed in, return null.
If (authorization = NULL ){
Return NULL;
}
// Singleton single-State mode is used below
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 access to Forum
Return new forumfactoryproxy (authorization, factory,
Factory. getpermissions (authorization ));
}

// The method for creating forum is completed by inheriting the subclass of forumfactory.
Public abstract Forum createforum (string name, string description)
Throws unauthorizedexception, forumalreadyexistsexception;

....

}

 

 

Because the current jive stores Forum posts and other content data through the database system, if you want to change it to the file system, this factory method forumfactory provides a dynamic interface:

Private Static string classname = "com. jivesoftware. Forum. database. dbforumfactory ";

You can use the self-developed Forum creation method to replace com. jivesoftware. Forum. database. dbforumfactory.

In the above Code, three modes are used. Besides the factory mode, Singleton single-State mode and proxy mode are used to authorize users to access forum, because there are two types of users to access forum: one is to register a user and the other is a tourist guest, then the corresponding permissions are different, and this permission runs through the entire system, so a proxy is created, similar to the concept of gateway, this effect can be achieved very well.

Look at catalogdaofactory in the Java pet store:

Public class catalogdaofactory {

 

/**

* This method develops a special subclass to implement the DAO mode.
* The specific subclass definition is in the deployment descriptor of J2EE.
*/

Public static catalogdao getdao () throws catalogdaosysexception {

Catalogdao catdao = NULL;

Try {

Initialcontext Ic = new initialcontext ();
// Dynamically Mount catalog_dao_class
// You can define your own catalog_dao_class so that you do not need to change too much code
// Complete the huge changes to the system.

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 obtains the implementation subclass of catalogdaofactory through the dynamic classloader classname. This implementation subclass is used to operate the catalog database in the Java pet store, you can customize your own implementation subclass based on different database types, and assign your subclass name to the catalog_dao_class variable.

It can be seen that the factory method indeed provides a very flexible and powerful dynamic expansion mechanism for the system structure. As long as we change the specific factory method, there is no need to change the system elsewhere, it is possible to change the system functions.

 

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.