Java Factory mode

Source: Internet
Author: User

Factory mode: Used primarily to instantiate classes with common interfaces, the factory pattern can dynamically determine which class should be instantiated.
Pattern of the factory model  

The factory model uses several forms mainly:
1: Simple Factory (Factory).
2: Factory Approach (Factory method).
3: Abstraction factory (abstract Factory).

Simple Factory (Factory)
Also called Static Factory, is the most simple structure in the three state of the Factory mode. There is a static method that accepts parameters and, depending on the parameters, returns instances of different classes that implement the same interface. Let's look at a specific example:
Suppose a factory, a few production washing machines, there are refrigerators, and air conditioning and so on.
We first define a common product interface for all products.

    public Interface product{}  

Then we make all the products in this factory must implement this interface

    public class Washer implements product{public        washer () {            System.out.println ("Washing machine was built");        }     }          public class Icebox implements product{public        icebox () {            System.out.println ("refrigerator was built");}     }          public class Aircondition implements product{public        icebox () {            System.out.println ("Air conditioner was built");        }     }  

  

Next we will write a factory class, which is responsible for the production of the above products
    public class Simplefactory {public                  static Product factory (String productName) throws exception{             if ( Productname.equals ("washer")) {                 return new washer ();             } else if (productname.equals ("Icebox")) {                 return new icebox ();             } else if (productname.equals ("aircondition")) {                 return new aircondition ();             } else{                 throw new Exception ("no Product");}}}       

Well, with this factory class, we can start placing orders, Simplefactory will decide what products to produce according to different order classes.

    public static void Main (string[] args) {         try {                   simplefactory.factory ("washer");                   Simplefactory.factory ("Icebox");                   Simplefactory.factory ("aircondition");                 } catch (Exception e) {             e.printstacktrace ();         }     }  

As can be seen from the above code, the core of a simple factory is a simplefactory class, he has the necessary logical judgment and the creation of all products, we only need to give him the order, we can get the product we want. This seems to be very convenient to use.
But, in fact, this simplefactory has a lot of limitations. First, every time we want to add a new product, we have to modify the original code of Simplefactory. Secondly, when we have a lot of products, and there are complex hierarchical relationship between products, this class must have complex logic judgment ability, and its code will continue to surge, which is the maintenance of the future is simply a horror of two words ...
There is, the whole system is heavily dependent on the Simplefactory class, as long as the Simplefactory Class A problem, the system will enter the state of the inability to work, which is also the most deadly point ....
These deficiencies will be resolved in two other states of the factory model.

Factory approach (Factory method)
The above code tells us that the simple factory is not simple, it is the core of the whole pattern, once he has a problem, the whole model will be affected and not to work, in order to reduce risk and for future maintenance, expansion to prepare, we need to refactor it, introduce the factory method.
The factory method defines the interface for the factory class and uses polymorphism to weaken the function of the factory class, the following is the definition of the factory interface:

    Public interface factory{Public       Product Create ();     }  

We'll define a product interface again.

public Interface product{}

  
A product class that implements the product interface

    public class Washer implements product{public        washer () {            System.out.println ("Washing machine was built");        }     }          public class Icebox implements product{public        icebox () {            System.out.println ("refrigerator was built");}     }          public class Aircondition implements product{public        icebox () {            System.out.println ("Air conditioner was built");        }     }  

  
The next step is the central part of the factory approach, which is the specific factory class that creates the Product object,

    The factory that created the washing machine public     class Createwasher implements factory{public         Product Create () {               return new washer ();         }     }          The factory that created the refrigerator public     class Createicebox implements factory{public         Product Create () {               return new icebox ();     }          Create Air Conditioning factory public     class Createaircondition implements factory{public         Product Create () {               return new Aircondition ();         }     }  

The code for creating a Product object from above shows that the main difference between a factory method and a simple factory is that a simple factory puts the function of creating a product in one class, while the factory method puts different products in different factory classes that implement the factory interface, so that if one of the factory classes has a problem, Other factory classes can also work properly, not affected each other, and then add new products, but only to add a factory interface factory to implement the class, you can achieve without modifying the existing code. But the factory method also has his limitations, that is when the face of the product has a complex hierarchical structure, for example, the factory in addition to the production of home appliances, but also the production of mobile phone products, so that the home appliance is a mobile phone is two major product families, the two families below contains a large number of products, each product has multiple models, This creates a complex product tree. If the factory method to design this product family system, you must create a corresponding factory class for each model of the product, when there are hundreds of or even thousands of products, also must have the corresponding hundreds of thousands of factory class, this is the legend of the class explosion, for future maintenance, is simply a disaster ....

Abstract Factory (Factory Method)
Abstract Factory: The intention is to create a series of interrelated or interdependent objects. <<java Design Patterns >>
I myself think that abstract factory is the introduction of the concept of classification management on the basis of factory methods ....
The factory method is used to create a product, it has no concept of classification, and the abstract factory is used to create a series of products, so the product classification becomes the focus of the abstract factory,
We continue to use the example above to illustrate:
Factory production of all products are used in uppercase letters to mark their models, such as refrigerators, there is "refrigerator-A", "refrigerator-B", the same, other products are also adhering to this number of rules, so there is a product family tree

Refrigerator:

    1. Refrigerator-A
    2. Refrigerator-B



Washing machine:

    1. Washer-A
    2. Washing machine-B


We can define two product interfaces for refrigerators and washing machines separately to classify them,

    Washing machine interface Public     interface washer{     }          //refrigerator Interface Public     interface icebox{     }  

  
Next, we create the specific product of these two interfaces separately

    Washing machine-A public     class Washera implements washer{public        Washera () {            System.out.println ("Washing machine-A was manufactured");        }     }          //washing machine-B public     class Washerb implements washer{public        Washerb () {            System.out.println ("Washing machine-B was made") ;        }     }          Refrigerator-A Public     class Iceboxa implements icebox{public        Iceboxa () {            System.out.println ("refrigerator-A was built");        }     }          Refrigerator-B Public     class ICEBOXB implements icebox{public        Iceboxb () {            System.out.println ("refrigerator-B was manufactured");        }     }  

To this, the product section we are ready, then we will deal with the factory section, we first define the factory behavior interface

    Public interface factory{Public            washer createwasher ();            Public icebox Createicebox ();     }  

Next I create a specific factory class, we according to the above product interface, the Model A's products are divided into a class, managed by a factory, the Model B product has another factory management, according to this classification, we can achieve the following two specific factory class

    Create a product factory public     class Factorya implements factory{            //Create a washing machine-a public            washer createwasher () {                 return new Washera ();            }                 Create refrigerator-A public            icebox Createicebox () {                 return new Iceboxa ();            }     }          Create a product factory public     class Factoryb implements factory{            //Create a washing machine-B public            Washer Createwasher () {                 return new Washerb ();            }                 Create refrigerator-B public            icebox Createicebox () {                 return new Iceboxb ();}     }  

  

 

In this way, our abstract factory is finished. As can be seen above, in the application I think the factory method and the abstract factory, have their own application scenarios, and there is no good or bad points, but before the application of the abstract factory, it is important to classify the objects created, Good product Classification rules can provide a clear idea for specific plant class selection calls and future expansions.

Note: This article references from: http://chjl2020.iteye.com/blog/265283

Java Factory mode

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.