The Factory mode of Java design mode

Source: Internet
Author: User

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).

    

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.

public class BMW320 {
Public BMW320 () {
System.out.println ("Manufacturing-->bmw320");
}
}

public class BMW523 {
Public BMW523 () {
System.out.println ("Manufacturing-->bmw523");
}
}

public class Customer {
public static void Main (string[] args) {
BMW320 bmw320 = new BMW320 ();
BMW523 bmw523 = new BMW523 ();
}
}
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.

Abstract class BMW {
Public BMW () {

}

}

public class BMW320 extends BMW {
Public BMW320 () {
System.out.println ("Manufacturing-->bmw320");
}
}
public class BMW523 extends bmw{
Public BMW523 () {
System.out.println ("Manufacturing-->bmw523");
}
}

public class Factory {
Public BMW createbmw (int type) {
Switch (type) {

    case 320:        return new BMW320();    case 523:        return new BMW523();    default:        break;    }    return null;}

}
Customer class:

public class Customer {
public static void Main (string[] args) {
Factory Factory = new Factory ();
BMW bmw320 = FACTORY.CREATEBMW (320);
BMW bmw523 = FACTORY.CREATEBMW (523);
}
}
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.

    下面我们从开闭原则(对扩展开放;对修改封闭)上来分析下简单工厂模式。当客户不再满足现有的车型号的时候,想要一种速度快的新型车,只要这种车符合抽象产品制定的合同,那么只要通知工厂类知道就可以被客户使用了。所以对产品部分来说,它是符合开闭原则的;但是工厂部分好像不太理想,因为每增加一种新型车,都要在工厂类中增加相应的创建业务逻辑(createBMW(int type)方法需要新增case),这显然是违背开闭原则的。可想而知对于新产品的加入,工厂类是很被动的。对于这样的工厂类,我们称它为全能类或者上帝类。     我们举的例子是最简单的情况,而在实际应用中,很可能产品是一个多层次的树状结构。由于简单工厂模式中只有一个工厂类来对应这些产品,所以这可能会把我们的上帝累坏了,也累坏了我们这些程序员。    于是工厂方法模式作为救世主出现了。 工厂类定义成了接口,而每新增的车种类型,就增加该车种类型对应工厂类的实现,这样工厂的设计就可以扩展了,而不必去修改原来的代码。

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:

Abstract class BMW {
Public BMW () {

}

}
public class BMW320 extends BMW {
Public BMW320 () {
System.out.println ("Manufacturing-->bmw320");
}
}
public class BMW523 extends bmw{
Public BMW523 () {
System.out.println ("Manufacturing-->bmw523");
}
}
To create a factory class:

Interface FACTORYBMW {
BMW CREATEBMW ();
}

public class FactoryBMW320 implements factorybmw{

@Overridepublic BMW320 createBMW() {    return new BMW320();}

}
public class FactoryBMW523 implements FACTORYBMW {br/> @Override
< p="">

    return new BMW523();}

}
Customer class:

public class Customer {
public static void Main (string[] args) {
FactoryBMW320 factoryBMW320 = new FactoryBMW320 ();
BMW320 bmw320 = FACTORYBMW320.CREATEBMW ();

    FactoryBMW523 factoryBMW523 = new FactoryBMW523();    BMW523 bmw523 = factoryBMW523.createBMW();}

}

The Factory mode of Java design 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.