Java Design mode Factory mode (simple Factory mode + Factory method mode)

Source: Internet
Author: User

Excerpted from http://blog.csdn.net/jason0539/article/details/23020989

In object-oriented programming, the most common approach is to create an object instance with a new operator, which is used to construct an object instance. In some cases, however, the new operator directly generates the object, causing some problems. For example, the creation of many types of objects requires a series of steps: You may need to calculate or get the initial settings of the object; Select which child object instance to generate; Or, you must generate some accessibility objects before you can build the objects you need. In these cases, the creation of a new object is a "process", not just an operation, like a gear drive in a large machine.

pattern Question : How can you easily and conveniently construct object instances without worrying about the details and complex process of constructing object instances?

Solution : Build a factory to create objects

Realize:

First, Introduction
1) There is no factory era: if there is no industrial revolution, if a customer wants a BMW, the general practice is to create a BMW car, and then to use.
2) Simple Factory mode: Later the Industrial Revolution occurred. Users do not have to create a BMW car. Because the customer has a factory to help him create a BMW. The factory can be built if you want a car. For example, want 320i series cars. The factory created this series of cars. That is, the factory can create products.
3) Factory method Mode era: In order to meet customers, BMW series more and more, such as 320i,523i,30li series of a factory can not create all the BMW series. It is then separated from a number of specific factories. Each specific factory creates a series. That is, the specific factory class can only create a specific product. But the BMW factory is still an abstraction. You need to designate a specific factory to produce the car.

4) Abstract Factory mode era: With the increasing demands of customers, BMW must be equipped with air-conditioning. So the factory started to produce BMW cars and needed air conditioners.

In the end, the customer just said to the BMW salesman: "I want 523i air-conditioned car, the salesman will give him 523i air-conditioned car directly." Instead of creating a BMW 523i air-conditioned car yourself.

This is the factory model.

Second, classification
The factory model provides a transition interface for creating objects to isolate the concrete process masks for creating objects to achieve greater flexibility.
The factory model can be divided into three categories:

1) Simple Factory mode (easy Factory)
2) Factory mode (Factory method)
3) Abstract Factory mode (Factory)

These three modes are progressively abstracted from top to bottom and more general.
In design mode, GOF divides the factory model into two categories: The Factory method Model (Factory) and the Abstract Factory mode (abstraction Factory).

The simple Factory is seen as a special case of the factory method pattern, which is grouped into one category.

Three, the difference
Factory method Mode:
An abstract product class that can derive a number of specific product classes.
An abstract factory class that can derive a number of specific factory classes.
Each specific factory class can only create an instance of a specific product class.
Abstract Factory mode:
Multiple abstract product classes, each abstract product class can derive multiple specific product classes.
An abstract factory class that can derive a number of specific factory classes.
Each specific factory class can create instances of more than one specific product class.
Difference:
The factory method pattern has only one abstract product class, and the abstract factory pattern has multiple.
Factory-mode-specific factory classes can only create instances of a specific product class, while abstract Factory mode may create multiple.
Both are available.

four, simple Factory mode
Build a factory (a function or a class method) to create a new object.
Distribution Description Intro: From scratch. Customers create their own BMW cars and then use them.

[Java]View Plaincopyprint?
  1. Public class BMW320 {
  2. Public BMW320 () {
  3. System.out.println ("Manufacturing-->bmw320");
  4. }
  5. }
  6. Public class BMW523 {
  7. Public BMW523 () {
  8. System.out.println ("Manufacturing-->bmw523");
  9. }
  10. }
  11. Public class Customer {
  12. public static void Main (string[] args) {
  13. BMW320 bmw320 = new BMW320 ();
  14. BMW523 bmw523 = new BMW523 ();
  15. }
  16. }

Customers need to know how to create a car, and the customer and the car are tightly coupled together. In order to reduce the coupling , there is the factory class, the creation of the BMW operation details are put into the factory, the customer directly use the factory to create a factory method, the introduction of the desired BMW model on the line, Without having to know the details of the creation. This is the Industrial Revolution: Simple Factory mode

That is, we create a factory class method to create new objects.

Product Category:

[Java]View Plaincopyprint?
  1. Abstract class BMW {
  2. Public BMW () {
  3. }
  4. }
  5. Public class BMW320 extends BMW {
  6. Public BMW320 () {
  7. System.out.println ("Manufacturing-->bmw320");
  8. }
  9. }
  10. Public class BMW523 extends bmw{
  11. Public BMW523 () {
  12. System.out.println ("Manufacturing-->bmw523");
  13. }
  14. }

Factory class:

[Java]View Plaincopyprint?
  1. Public class Factory {
  2. Public BMW CREATEBMW (int type) {
  3. switch (type) {
  4. case :
  5. return new BMW320 ();
  6. Case 523:
  7. return new BMW523 ();
  8. Default:
  9. Break ;
  10. }
  11. return null;
  12. }
  13. }


Customer class:

[Java]View Plaincopyprint?
    1. public class  customer {  
    2.     public < span class= "keyword" >static void main (string[] args)  {  
    3.         factory factory  = new factory ();   
    4.      &NBSP;&NBSP;&NBSP;&NBSP;BMW&NBSP;BMW320&NBSP;=&NBSP;FACTORY.CREATEBMW (320);  
    5.         bmw bmw523 =  FACTORY.CREATEBMW (523)   
    6.     }  
    7. }&NBSP;&NBSP;

The simple factory model is also called the Static factory method mode. Renaming can tell that this pattern must be simple. The purpose of its existence is simple: Define an interface for creating objects.
Let's take a look at its composition:
1) Factory class role: This is the core of this model, contains certain business logic and judgment logic, used to create the product
2) Abstract Product role: It is generally the product of the specific inheritance of the parent class or implementation of the interface.
3) Specific product roles: the object created by the factory class is an instance of this role. Implemented in Java by a concrete class.

Below we analyze the Simple Factory mode from the opening and closing principle (open for expansion; closed for modification). When customers no longer meet the existing model of the car, want a fast new type of car, as long as the car conforms to the abstract product formulation contract, so long as the notice factory class know can be used by customers. So for the part of the product, it is in accordance with the opening and shutting principle, but the factory part seems not ideal,because every new type of vehicle is added, it is necessary to add the corresponding creation business logic in the factory class (the CREATEBMW (int type) method requires a new case), which is obviously contrary to the opening and closing principle.。 It can be imagined that the introduction of new products, factory class is very passive. For such a factory class, we call it the Almighty class or the God class.
Our example is the simplest case, and in practical applications it is possible that the product is a multi-layered tree structure. Since there is only one factory class in the simple factory model that corresponds to these products, this may make our God tired and tired of our programmers.
So the factory method model as Savior appeared. The factory class is defined as an interface, and each new type of vehicle is added to the implementation of the plant class, so that the design of the plant can be expanded without having to modify the original code.
Five, factory method mode
The factory method pattern removes the static property of the factory method in the simple Factory mode, allowing it to inherit from the quilt class. The pressure to concentrate on factory methods in a simple factory model can be shared by different factory subclasses in the factory method model.
The factory method pattern consists of:
1) Abstract Factory role: This is the core of the factory method pattern, which is independent of the application. is the interface that the specific factory role must implement or the parent class that must inherit. In Java it is implemented by an abstract class or interface.
2) Specific factory role: it contains code related to the specific business logic. Called by the application to create an object that corresponds to a specific product.
3) Abstract Product role: It is the parent of a specific product inheritance or an interface implemented. In Java, there are generally abstract classes or interfaces to implement.
4) Specific product roles: the object created by the specific factory role is an instance of this role. Implemented in Java by a specific class.
The factory method pattern uses multiple subclasses that inherit from the abstract factory role to replace the "God Class" in the simple factory pattern. As mentioned above, this shares the pressure of the object, and this makes the structure flexible--when a new product is produced, it can be used by the customer as long as it is generated by the contract provided by the abstract product role and the abstract factory role, without having to modify any existing code. We can see that the structure of the factory role is also in line with the closed principle!

The code is as follows:

Product Category:

[Java]View Plaincopyprint?
  1. Abstract class BMW {
  2. Public BMW () {
  3. }
  4. }
  5. Public class BMW320 extends BMW {
  6. Public BMW320 () {
  7. System.out.println ("Manufacturing-->bmw320");
  8. }
  9. }
  10. Public class BMW523 extends bmw{
  11. Public BMW523 () {
  12. System.out.println ("Manufacturing-->bmw523");
  13. }
  14. }


To create a factory class:

[Java]View Plaincopyprint?
  1. Interface FACTORYBMW {
  2. BMW CREATEBMW ();
  3. }
  4. Public class FactoryBMW320 implements factorybmw{
  5. @Override
  6. Public BMW320 CREATEBMW () {
  7. return new BMW320 ();
  8. }
  9. }
  10. Public class FactoryBMW523 implements FACTORYBMW {
  11. @Override
  12. Public BMW523 CREATEBMW () {
  13. return new BMW523 ();
  14. }
  15. }


Customer class:

[Java]View Plaincopyprint?
  1. Public class Customer {
  2. public static void Main (string[] args) {
  3. FactoryBMW320 factoryBMW320 = new FactoryBMW320 ();
  4. BMW320 bmw320 = FACTORYBMW320.CREATEBMW ();
  5. FactoryBMW523 factoryBMW523 = new FactoryBMW523 ();
  6. BMW523 bmw523 = FACTORYBMW523.CREATEBMW ();
  7. }
  8. }


The factory method pattern seems to have been perfectly wrapped in the creation of objects, allowing the client to process only the interfaces provided by the abstract product role, but to multiply the number of objects. When the product category is very long, there will be a large number of corresponding plant objects, which is not what we want.

The above is simple Factory mode, factory method mode, abstract Factory mode here.

Java Design mode Factory mode (simple Factory mode + Factory method 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.