Factory mode definition: Provide interfaces that create objects.
Why? The factory model is our most common mode. The famous JIVE Forum uses a large number of factory models, and the factory model can be said to be everywhere in the Java program system.
Why is the factory model so common? Because the plant mode is equivalent to the new instance object, we often generate instance objects according to class Class, such as A a = new a () factory model is also used to create instance objects, so you will have multiple minds when New. Can I consider practical factory models, although doing this, may do more work, but will give you more scalability and minimal modifications.
We use class SAMPLE as an example, if we want to create instance objects of Sample:
Sample sample = new sample ();
However, the actual situation is, usually we have to do some initialization work when you create a Sample instance, such as assigning the query database.
First of all, we think that you can use the Sample constructor, which generates an instance to be written:
Sample sample = new sample; parameter;
However, if the initialization work made when creating a Sample instance is not like assigning a simple matter, it may be a long code. If you also write into the constructor, then your code is ugly (just need refactor reach).
Why is it difficult to say that beginners may not have this feeling, we analyze the following, if it is a long code, it means that there are many work to do, put a lot of work into a method, equivalent to putting a lot of eggs In a basket, it is very dangerous, which is also a principle of Java-oriented objects. Object-oriented package (encapsulation) and dispatch tell us, try to assign a long code to a "cutting" into each section, will each Segment is then "package" (reducing the coupling between segments and segments), which will disperse the risk, if you need to modify, as long as you change each paragraph, you will not happen.
In this example, first, we need to separate the work of the creation instance and the use of the instance, that is, let the large amount of initialization required for the creation instance from separating from the Sample constructor.
At this time, we need Factory factory model to generate an object, and you cannot use the simple new sample (parameter) above. Also, if Sample has inherits such as mysample, according to the interface programming, we need to abstract Sample into an interface. Now Sample is an interface, there are two subclass mysample and hissample. We have to instantiate them, as follows:
Sample mysample = new mysample (); sample hissample = new Hissample ();
As the project is in-depth, Sample may "give birth to a lot of son", then we have to instantiate these sons, even worse, may also modify the previous code: Joining the instance of the son later. This is unavoidable in traditional programs.
But if you have a conscious use of factory models, these troubles are there.
Factory method You will establish a factory specializing in the production of Sample instances:
Public Class Factory {public Static Sample Creator (INT which) {// getClass generates SAMPLE to be loaded with a dynamic class loading. IF (Which == 1) Return New Samplea (); Else If (Which == 2) Return New Sampleb ();}}
So in your program, if you want to instantiate Sample.
Sample Samplea = Factory.creator (1); This, throughout the case, the concrete subclass of SAMPLE does not involve the package effect, and the opportunity to reduce the error modification can be reduced. This principle can be used very popular: it is specific to do The more you get, the easier it is wrong. This person who has made specific work is deeply appreciated. On the contrary, the higher the official, the more abstract, the more abstract, the less wrong, the less, it seems to be Can you realize the truth from your programming? Hehe.
Use the factory method to pay attention to several roles, first you want to define the product interface, as the sample above, the product interface has the implementation class, such as SAMPLEA, after another, with a Factory class, used to generate product Sample, as shown below, The homemost side is the object of the production:
Further, a little more complicated is to expand at the factory class, and the factory class also has inherits its implementation of CONCRETEFACTeFactory.
Abstract factory factory models are: Factory Method Abstract Factory (ABSTRACT FACTORY).
These two patterns differ in the complexity of the need to create objects. If we create objects, it is more complicated, as in the factory method, you create an object Sample, if we have new product interface Sample2.
Here, it is assumed: Sample has two Concrete class Samplea and Samleb, and Sample2 also has two Concrete class Sample2a and Sampleb2.
Then, we will turn the Factory in the above example into an abstract class, and the common partial package is in an abstract class. Different parts use subclass implementation, the following is to expand the Factory in the above example into 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}}
From the above, two factories have produced a set of Sample and Sample2, maybe you will have questions, why can't I use two factory methods to produce SAMPLE and SAMPLE2?
The abstract factory has another key point because there is a connection between the SimpleFactory, the production of SAMPLE and production of SAMPLE2, so it is necessary to bundle these two methods in a class, this factory class has its own characteristics, perhaps The manufacturing process is unified, such as: the manufacturing process is relatively simple, so the name is SimpleFactory.
In practical applications, the factory method is used more, and it is combined with the dynamic loader.
Example
We take Jive's ForumFactory as an example, this example we discussed in the previous Singleton mode, now discuss its factory model:
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 Singleton Dynamic Mode IF (Factory == Null) {synchronized (initlock) {if (factory == Null ) {... try {// Dynamic reprint class C = Class.Forname (classname); factory = (forumfactory) c.newinstance ();} catch (exception e) {return null;}}}}}}}}} // Now, return proxy. Used to limit the authorization of the access Return New ForumFactoryProxy (Authorization, Factory, Factory.getPermissions); Forum CREATEFORUM (STR ingname, string description) throws unauthorizedException, forumalreadyexistSException; ....} Because the current jive is to store content data such as the forum post through the database system, if you want to change to implement the file system, this factory method forumfactory provides a dynamic interface. :
Private static string classname = "com.jivesoftware.forum.database.dbforumfactory";
You can use your own development to create Forum instead of com.jivesoftware.forum.database.dbforumFactory.
In a total of three modes in the above code, in addition to the factory model, there is a Singleton monetary mode, as well as the Proxy mode, the Proxy mode is mainly used to authorize the user's access to the Forum, because there are two people: one Is a registered user is a tourist GUEST, then the corresponding permissions are different, and this permission is throughout the system, so establish a proxy, similar gateway concept, can achieve this effect very well.
Take a look at the CatalogDaFactory in the Java pet shop:
Public class catalogdaofactory {/ ** * This method makes a special subclass to implement DAO mode. * The specific subclass definition is in the J2EE deployment descriptor. * / Public static CatalogDAO getDAO () throws CatalogDAOSysException {CatalogDAO catDao = null; try {InitialContext ic = new InitialContext (); // can be dynamically loaded CATALOG_DAO_CLASS // define their own CATALOG_DAO_CLASS, so that without changing much of the code // In the premise, the huge change of the system is completed. 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 a CatalogDaFactory implementation subclass by dynamic types, this implementation subclass is used to operate the Catalog database in Java pet stores, and users can customize according to the type of database. Both specific implementation of their specific implementation, the names of their subclasses can be used as the Catalog_DAO_CLASS variable.
It can be seen that the factory method does provide a very flexible dynamic expansion mechanism for the system structure, as long as we replace the specific factory method, there may no need to change the system elsewhere, it is possible to change the system function.