Factory (factory mode) in Creation Mode)

Source: Internet
Author: User

Definition: Creation
Object interface.



Why?





The factory model is our most commonly used model, the famous jive Forum
The factory mode is widely used. 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 a new instance object, we often need to generate instance objects according to class, such as a A = new ()
The factory mode is also used to create instance objects, so there will be multiple eyes in the future for new users, whether the practical factory mode can be considered, although doing so, may do more work, but it will bring greater scalability to your system.
Scalability and minimal modification.

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

Sample = new
Sample ();

However, the actual situation is that we usually create a sample
Instance initialization, such as assigning values to query databases.

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

Sample = new
Sample (parameter );

However, if
Initialization is not a simple task like assigning values. It may be a long piece of code. If it is also written into the constructor, your code will be ugly (refactor reorganization is required ).

Why is the code ugly? This may not be the case for beginners. We will analyze the following:
A long piece of code indicates a lot of work to be done. It is very dangerous to put a lot of work into one method, which is equivalent to putting a lot of eggs in one basket, this is also based on the Java object-oriented principle. The object-oriented encapsulation (encapsulation) and distributed (Delegation) tell us to try to keep the length
The code is assigned "cut" into each segment, and each segment is "encapsulated" (reducing the coupling and association between segments). In this way, the risks are dispersed. If you need to modify the segments in the future, as long as you change each segment, no further action will occur
Hundreds of things.

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
The generated object cannot be used with the simple new sample (parameter) above ). Also, if the sample has an inheritance such as mysample,
According to the interface-oriented programming, We need to abstract the sample into an interface. Now sample is an interface and has two subclasses: mysample and hissample.
When we want to instantiate them, we will see the following:

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

As the project goes deeper, the sample may be"
",
We need to instantiate these sons one by one. Even worse, we may also need to modify the previous Code: add the son-generated instance, which is unavoidable in traditional programs.

But if you consciously use the factory model from the very beginning,
These troubles are gone.

Factory method




You will create a dedicated
Factory that produces 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
Sample.

Sample
Samplea = factory. creator (1 );

In this way, the sample
Sub-classes to reduce the chance of modifying errors when encapsulation is achieved. This principle can be used in a common sense as follows: the more specific things are done, the easier it is to set errors. every person who has done a specific job has a deep understanding of it.
Yes, on the contrary, the more the officers do, the more abstract the words are, the less likely the fan errors are. 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 products
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 method)
Abstract Factory ).

The difference between the two modes is that
The complexity of the object to be created. If the method for creating an object becomes complicated, for example, the factory method above creates an object sample, as shown in
If we 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
In the example above
Factory expands to 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
}

}

 

From the above, we can see that the two factories each produce a set of samples.
And sample2, maybe you will doubt, why can't I use two factory methods to produce sample and sample2 respectively?

The abstract factory has another key point because
In simplefactory, there is a certain relationship between the method for producing sample and the method for producing sample2. Therefore, we need to bind these two methods to a class. This factory class has its own characteristics.
Maybe the manufacturing process is uniform. 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

We use jive's
Forumfactory is used as an example. This example is discussed in the previous Singleton mode. Now we will discuss the 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
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 is stored through the database system
If you want to change the content data such as Forum posts to file system implementation, the factory method forumfactory provides dynamic interfaces:

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

You can use a self-developed method to create a forum
Instead of COM. jivesoftware. Forum. database. dbforumfactory.

In the above Code, three modes are shared,
In addition to the factory mode, there are Singleton single-State mode and proxy mode. The proxy mode is mainly used to authorize users to access forum, because there are two types of users accessing Forum:
One is to register a user and the other is a tourist guest, so the corresponding permissions are different, and this permission runs through the entire system. Therefore, it is good to establish a proxy, similar to the concept of gateway.
Achieve this effect.

Look at the Java pet store's
Catalogdaofactory:

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
Catdao obtains the specific implementation subclass of catalogdaofactory through the dynamic classloader classname. This implementation subclass is used in Java pet store for operation.
Catalog Database, you can customize your own implementation subclass based on the database type, and give your subclass name to the catalog_dao_class variable.

It can be seen that the factory method does provide a flexible and powerful dynamic expansion mechanism for the system structure, as long as we change the specific
In the factory method, the system functions may be changed without any change elsewhere.

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.