1. Definition of the factory model
Factory models are used in very high frequency and we can always see them in development. It is defined as: Define an interface for creating a object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. That is, define an interface for creating objects, so that subclasses decide which class to instantiate. The factory method defers the instantiation of a class to its subclasses. The common class diagram for the factory method pattern is as follows:
, the product abstract class is responsible for defining the commonality of the products, implementing the most abstract definition of things, creator as abstract factory classes, and how to create product classes from the concrete implementation of the factory Concretecreator to complete. Let's take a look at the generic template code:
Public abstract class product () The common method of the product class, which has been implemented//implemented public logic}public abstract void method2 ();//non-public method, required Subclass-Specific Implementation}
Specific product classes can have multiple, all inheriting with abstract class product, as follows:
public class ConcreateProduct1 extends Product {@Overridepublic void Method2 () {//product1 business logic}}public class ConcreateProduct2 extends Product {@Overridepublic void Method2 () {//product2 business logic}}
The abstract factory class is responsible for defining the production object, the code is as follows:
Public abstract class Creator {//Creates a product object whose input parameter type can be set by itself public abstract <t extends product> T createproduct (class& Lt T> clazz);}
The generic is used here, and the incoming object must be an implementation class of the Product abstract class. Specifically how to produce a product object, is implemented by the specific factory class, the specific factory class inherits this abstract factory class:
public class Concretecreator extends Creator {@Overridepublic <t extends product> T createproduct (class<t> cl Azz) {Product Product = null;try {Product = (product) class.forname (Clazz.getname ()). Newinstance ();} catch (Exception e) { Exception handling E.printstacktrace ();} Return (T) product;}}
With this design, we can produce the product randomly in the test class, and see the following test class:
public class Factorytest {public static void main (string[] args) {Creator factory = new Concretecreator (); Product Product1 = factory.createproduct (Concreteproduct1.class); Create different products by different classes product Product2 = Factory.createproduct (Concreteproduct2.class); */* Continue with other business processes below * * }}
Here is an example of Nu WA made man to illustrate the practical application of the factory model.
2. Explain the factory model with female Volute
Now Nu WA to build a man, she will build three kinds of people: white, yellow and black people. How to build it? She had to have a factory that could produce human beings (something like a gossip stove), and the factory had to make her produce different races. Everyone has two properties: skin color and speech. So now we're going to design the procedure for the female volute, first of all, let's look at the class diagram of making people:
Abstract interface Human is human, inside there are two methods, GetColor get skin color, talk conversation. The following three specific human implementation classes, respectively, to achieve three races. According to the factory model, there should be an abstract factory, abstracthumanfactory assume this responsibility, there is an abstract method Createhuman, that humanfactory is to implement the class, to achieve the method of the abstract factory. Let's look at the specific implementation:
Public interface Human {public void GetColor ();//people have different colors public void talk ();//People speak}
Next to the different implementations of the Human interface:
public class Blackhuman implements Human {///Black @overridepublic void GetColor () {System.out.println ("Blacks");} @Overridepublic void Talk () {System.out.println (' Black Man ');}} public class Human implements Human {//Yellow @overridepublic void GetColor () {System.out.println ("Yellow");} @Overridepublic void Talk () {System.out.println (' Yellow Man ');}} public class Whitehuman implements Human {//Caucasian @overridepublic void GetColor () {System.out.println ("white");} @Overridepublic void Talk () {System.out.println (' white Man ');}}
Well, the man's mold, now nu wa to start to build gossip stove, so Nu WA began to draw gossip stove model:
Public abstract class Abstracthumanfactory{public abstract <t extends human> T createhuman (class<t> clazz); /Note that T must be an implementation class for human, because you want to build human.
Then Nu WA began to concretely realize this gossip stove ...
public class Humanfactory extends Abstracthumanfactory {@Overridepublic <t extends human> T Createhuman (class<t > Clazz) {Human Human = null;try {Human = (Product) class.forname (Clazz.getname ()). Newinstance ();} catch (Exception e) {//Exception handling SYSTEM.OUT.PRINTLN ("Race generation Error");} return (T) human;}}
Well, now there are races, gossip stove also has, the rest is to collect loess, and then ordered the gossip furnace began to produce:
public class Factorytest {public static void main (string[] args) {abstracthumanfactory Bagualu = new Hunmanfactory (); Human Blackman = Bagualu.createhuman (Blackhuman.class); The Negro was born Human Yellowman = Bagualu.createhuman (Yellohuman.class); Yellow was born human WhiteMan = Bagualu.createhuman (Whitehuman.class); The white man was born }}
Nu WA is so artificial out of ... This is the Factory mode!
3. Expansion of the factory model3.1 Static Factory mode
We also use the above Nu WA made man's example, now Nu wa is thinking about a problem: I now only need a factory can produce people, why I want specific factory object? I just need to use the static method. Such a thought, so Nu WA began to abstracthumanfactory abstract class removed, only retained the Humanfactory class, at the same time the Createhuman method set to static type, done!
public class Humanfactory {@Overridepublic static <t extends human> T createhuman (class<t> clazz) {Human Human = null;try {human = (Product) class.forname (Clazz.getname ()). Newinstance ();} catch (Exception e) {//exception handling System.out.prin TLN ("Race produces errors");} return (T) human;}}
Then Nu wa made people without new what gossip stove, directly with the Humanfactory class call on the line:
Human Blackman = Humanfactory.createhuman (Blackhuman.class);
This is the static Factory mode, in the actual project, according to the requirements can be set to static factory class, but the disadvantage is the extension is difficult, if a factory, do not need to expand, can be so designed, is still very common.
more than 3.2 factory models
We also use Nu WA to make people as an example, later Nu WA thought, this person can not talk about it, but also have different attributes to kill, if in a gossip stove, in addition to new a person, but also to different people set different attributes, so that, gossip stove a little unbearable ah ... It's a little messy. But she thought of a way, each person to get a gossip stove, different gossip stove specializing in the production of different races, so that the structure is clear, she in the creation of the people when they choose which gossip stove associated with the line. As follows:
In this case Abstracthumanfactory abstract class we are going to rewrite:
Public abstract class Abstracthumanfactory {public abstract Human Createhuman ();}
Note that there is no need to pass the parameters of the related classes in the abstract, because each specific factory is already very clear about its responsibilities: to create the Product class object of its own responsibility. So different factories to implement their own Createhuman method can:
public class Blackhumanfactory extends Abstracthumanfactory {public Human Createhuman () {return new Blackhuman ();}} public class Yellowhumanfactory extends Abstracthumanfactory {public Human Createhuman () {return new Yellowhuman ();}} public class Whitehumanfactory extends Abstracthumanfactory {public Human Createhuman () {return new Whitehuman ();}}
So three different factories were produced, each corresponding to the production of their own corresponding species. So now Nu WA made people can not use a gossip stove, division of cooperation, each does not affect!
public class Factorytest {public static void main (string[] args) {Human Blackman = new Blackhumanfactory (). Createhuman (); The Negro was born Human Yellowman = new Yellowhumanfactory (). Createhuman (); Yellow was born human WhiteMan = new Whitehumanfactory (). Createhuman (); The white man was born }}
The benefits of this factory model are clear responsibilities, simple structure, but have a certain impact on scalability and maintainability, because if you want to extend a product class, you need to create a corresponding factory class, which increases the difficulty of expansion. Because the number of factory classes and product classes is the same, the relationship between the two objects needs to be considered during maintenance. But this pattern is still very common.
3.3 Alternate Singleton mode
The previous chapter introduces the singleton pattern, and points out some disadvantages of single and multiple cases, but can we use Factory mode to implement a single-case mode function? The answer is yes, the core requirement of the singleton pattern is that there is only one object in memory, and a factory method pattern can also produce only one object in memory. See below:
The Singleton class defines a private, parameterless construction method that does not allow the creation of objects by means of new, and the Singleton class does not define a singleton object by itself, because it is obtained through the factory.
public class Singleton {private Singleton () {}public void dosomething () {//Business process}}
Since Singleton cannot establish an object through normal channels, how does singletonfactory create a singleton object? The answer is created by reflection:
public class Singletonfactory {private static Singleton instance;static {try {class clazz = Class.forName (singleton.class . GetName ());//Get the parameterless construction method Constructor constructor = Clazz.getdeclaredconstructor ();// Set the parameterless construction method to access constructor.setaccessible (TRUE);//Generate an Instance object instance = (Singleton) constructor.newinstance ();} catch (Exception e) {//exception handling}}public static Singleton getinstance () {return instance;}}
The above creates a singleton object through the factory method pattern, which can continue to expand, and in one project can produce a singleton constructor, all classes that need to produce a singleton follow a certain rule (the construction method is private), and then by extending the framework, Only one instance can be obtained by entering a type.
3.4 Deferred initialization
What is deferred initialization (lazy initialization)? When an object is used, it is not released immediately, and the factory class remains in its initial state, waiting to be used again. Lazy initialization is an extended application of Factory mode, and its general class is represented as follows:
Productfactory is responsible for the creation of the product class object, and generates a cache through the PRMAP variable, reserved for objects that need to be reused again:
public class Productfactory {private static final map<string, product> prmap = new HashMap ();p ublic static Synchroni Zed Product Createproduct (String type) throws Exception {Product Product = null;//If the object is already in the map if (Prmap.containskey ( Type) {Product = Prmap.get (type);} else {if (Type.equals ("Product1")) {Product = new ConcreteProduct1 ();} else {product = new ConcreteProduct2 ();} Prmap.put (type, product);} return product;}}
The code is relatively simple, by defining a map container to hold all the resulting objects, each time in the new object to determine whether there is a map, there is no more new, direct fetch. In addition, each time new is over an object, it is also placed in the map to facilitate the next call.
Lazy loading is useful, such as the JDBC Connection database, which requires setting up a maxconnections maximum number of connections, which is the maximum number of instances in memory.
4. Application of Factory mode
Advantages:
1. The factory model has good encapsulation, the code structure is clear, also facilitates the expansion. In the case of adding product classes, you can complete the "embrace change" by simply modifying the specific factory class or extending a factory class appropriately.
2. The Factory mode can block the product class. This is very important, how the implementation of the product class changes, the caller does not have a relationship, only need to care about the interface of the product, as long as the interface remains the same, the system's upper module does not need to change.
3. The factory model is a typical decoupling framework. High-level modules only need to know the product's abstract class, other implementation classes do not care.
Factory mode is introduced so much, if the error, welcome to the message ~
___________________________________________________________________________________________________________ __________________________________________
-----willing to share and progress together!
-----More articles please see: http://blog.csdn.net/eson_15
"Java design mode" Factory (Factory) mode