Design pattern (2) - Detailed factory pattern

I. Introduction

  Today this blog to introduce design patterns very commonly used - the factory model. In fact, the factory model name only a general term, it is divided into simple factory, factory method and abstract factory. Next, I have to introduce them separately.


Second, the text

 2.1 Interface for programming

  Is a programming interface for the design principles of object-oriented programming language, which indicates that we are in the process of programming, you should try to use the interface to our specific references to objects instead of using concrete classes The goal is to use this object code is not overly dependent on the specific type. If we are using the interface, rather than specific types, then we retain some flexibility for the code here, because we can simply replace another subclass, without affecting the code that uses it.

Note: talking about here is the interface does not require interface, which indicates that all of the parent type, can be an interface, can be an abstract class, or even a general category, it refers to a certain type of upper layer type;

  Achieved factory method is to follow this principle, in order to achieve a decoupling.


 Simple Factory 2.2

  Simple plant and its name, very simple to implement, it is defined as follows:

When you create an object is not exposed to the user details to create an object, only to provide a common interface to create objects through this interface;

  Simple plant will create a code having a common parent class object separate out, placed into a class, and provides an interface, the object can be created by calling this interface, but which is specifically created child class object is determined by simple factory . We directly understood by the following code. Suppose we need to create Aproducts, and Aproducts in four specific products, as follows:

// A类产品
abstract class A {
}

// 以下均为具体产品
class A1 extends A {
}

class A2 extends A{
}

class A3 extends A{
}

  Assuming that the above three specific product numbers are 1、2、3, we need to select a product needs to be created according to the number in the code, so we can write:

public static void main(String[] args) throws IOException {
    int type = System.in.read();
    A a = null;
    if (type == 1) {
        a = new A1();
    } else if (type == 2) {
        a = new A2();
    } else if (type == 3) {
        a = new A3();
    } else {
        System.out.println("no product");
    }
}

  Obviously, the above code is very bad, it causes the code to create an object with a specific object types have a great coupling. From the perspective of code reuse, suppose we want to create in the rest of the Aproduct, every place needs to be used to write on the above code; then in terms of scalability, if we need to add a new product A4, or modify the number of products that for each use of the code above places need to be modified, greatly increasing the difficulty of maintaining the program, which is harmful high coupling. So we need to decouple the above code, so the code to create specific logic and object separation. According to the experience of our programming, which can be performed:

class AFactory {
    public static A createA(int type) {
        if (type == 1) {
            return new A1();
        } else if (type == 2) {
            return new A2();
        } else if (type == 3) {
            return new A3();
        } else {
            System.out.println("no product");
        }
        return null;
    }
}

  These are simple plants. Public method we will create a process of extracting the object to a class, the return value is the common parent of these products, so we call the factory directly above where it is needed to create the object. And the method hides the specific type of the object, reducing the particular type of coupling. And when you need to modify only need to modify the method, the code calls for it is hidden.

  In fact, the simple design of the plant is not a pattern , it is a good habit when we coded - Code extract reusable, easy to reuse.


 2.3 Factory Method

  Let's take a look at the definition factory method:

Factory method pattern defines a created object's interface, but the interface is implemented by a subclass, the subclass decided to target the specific needs created. The factory method to create an object of class work delayed until the child;

  Factory method first defines a top-class facility, which provides a method for creating an object, but this method generally do not have to implement because it does not determine which object needs to be created. The specific object creation work is handed over to a subclass of the factory implementation. Under the responsibility of the programmer subclass of the factory, to implement the interface method in the parent factory to create objects, you need to create specific types of the subclass. Choose a different sub-class factory, will naturally create different objects. Let's take a look through the code.

  Suppose we now need to create the Producttype of product, but Productthere are two types of specific products, and Producttypes of products have an showoperation, as follows:

// 抽象的产品
abstract class Product {
    // 定义产品的公共方法
    abstract void show();
}

// 具体产品1
class Product1 extends Product{
    @Override
    void show() {
        System.out.println("Product1");
    }
}

// 具体产品2
class Product2 extends Product{
    @Override
    void show() {
        System.out.println("Product2");
    }
}

  We need factories Factoryto create this product, but we want to have multiple factories, each factory is responsible for creating different types of products. But we hope that these plants there is no difference in use, do not want to know the specific use of which factory just want to use it, I was able to create needed products. So we can create a common factory class, but it's just a common standard, and will not work, but the real work is based on standard construction of this plant, which are responsible for creating Product1and Product2:

// 抽象的工厂类提供了一个创建对象的接口
// 它是具体工厂的一个标准
abstract class Factory {
    /**
     * 创建对象的接口,但是没有实现,由子类来决定创建什么对象
     * 不需要在意产品的具体类型,因为它们都有公共的父类
     */
    abstract public Product createProduct();
}

// 子类实现抽象的工厂类,实现具体的创建对象的接口
class Factory1 extends Factory{
    @Override
    public Product createProduct() {
        // Factory1创建Product1
        return new Product1();
    }
}

class Factory2 extends Factory{
    @Override
    public Product createProduct() {
        // Factory2创建Product2
        return new Product2();
    }
}

  So now we can create a specific object. We chose different plants to create different products:

public static void main(String[] args) {
    // 根据选择的工厂不同,创建的产品也不同
    // 但是不需要在意产品的具体类型,因为产品有公共的分类Product

    // 选择工厂1
    Factory f1 = new Factory1();
    Product p1 = f1.createProduct();
    p1.show();  // 执行Product1的show方法

    // 选择工厂2
    Factory f2 = new Factory2();
    Product p2 = f2.createProduct();
    p2.show();  // 执行Product2的show方法
}

// 执行结果
Product1
Product2

  You can see, we created according to different plants, to produce the final product is different, but no matter what the choices are a factory, you can use Factorya type reference, regardless of which is to create a product that can be used Productto receive, and we they do not care about points to which factory or which product we really care about except that they can make the right moves, nothing more, which is the benefits of interface-oriented programming.


 2.4 Abstract Factory pattern

  Abstract plant is actually based on a total factory method, which is defined as follows:

Abstract factory pattern provides an interface for creating a set of related objects, but do not need to explicitly specify the version of these objects;

  Defined above description, the abstract factory pattern is used to produce a set of a plurality of interrelated objects, but do not need to care about the specific type of object, so you can make these objects and using them decouple code. Method to create each object in the series of the object, is the use of factory methods described above. In other words, the abstract factory contains a number of factory method. We still look at and see through a case.

  Suppose we want to produce a car Car, for simplicity, it is assumed that the car windows and wheels composed of two parts, and different types of wheels and windows can be composed of different cars. We need some different types of wheels and windows, type the following defines an abstract Wheelrepresentation wheels, but defines two different types of wheels, a rubber wheel, used in the production of cars, while a wooden wheel is used to produce wooden cart;

// 轮子抽象类
abstract class Wheel {
}

// 轮子的第一个产品:橡胶轮子
class RubberWheel extends Wheel {
}

// 轮子的第二个产品:木头轮子
class WoodenWheel extends Wheel {
}

  Then we also need the windows, so we define an abstract class Windowrepresents a window, but there are two kinds of glass windows and wood windows subclasses:

// 窗户抽象类
abstract class Window {
}

// 玻璃窗户
class GlassWindow extends Window {
}

// 木头窗户
class WoodenWindow extends Window {
}

  Then we need to have a Carclass represents car, this Carby wheels and windows composition:

// 车
class Car {
    // 车轮
    Wheel wheel;
    // 车窗
    Window window;

    public Car(Wheel wheel, Window window) {
        this.wheel = wheel;
        this.window = window;
    }
}

  Next, we must consider how to produce different types of car. We need a factory that can produce wheels, can also produce windows, and then the wheels and windows can also be combined to form themselves into a car. So we define a car factory, it has two abstract methods for the production of wheels and windows, as well as a method for assembling cars. Assembly of the vehicle is fixed, the wheels and the window is to be combined, however, depending on the production needs of the vehicle, may require different parts, so the following class definition of only producing standard vehicles, the specific car how to generate What parts need to be used, which requires subclasses to decide according to their functions:

// 造车工厂:需要生产一系列车需要的零件,组合成车
abstract class CarFactory {
    // 造轮子
    abstract Wheel createWheel();

    // 造窗户
    abstract Window createWindow();

    // 将零件组合成车,这个过程是固定的,所以不需要在子类中实现
     Car createCar() {
        Wheel wheel = createWheel();
        Window window = createWindow();
        return new Car(wheel, window);
    }
}

  We hope that we have two factories, a generation of cars, the use of glass windows and rubber wheels; generating a wooden cart, wheel using wood and wood windows. So we need to inherit defined above standard production car CarFactory, and then select the parts they need to create, as follows:

// 制造小汽车
class CompactCarFactory extends CarFactory{
    @Override
    Wheel createWheel() {
        // 小汽车需要橡胶轮子
        return new RubberWheel();
    }

    @Override
    Window createWindow() {
        // 徐爱汽车需要玻璃窗户
        return new GlassWindow();
    }
}


// 制造木头车
class WoodenCarFactory extends CarFactory{
    @Override
    Wheel createWheel() {
        // 木头车需要木头轮子
        return new WoodenWheel();
    }

    @Override
    Window createWindow() {
        // 木头车需要木头窗户
        return new WoodenWindow();
    }
}

  Now then, depending on our choice of the plant, it is possible to produce different types of cars, the following code uses the abstract factory. If we choose a car factory, the production car that call interface, the actual production is glass windows and rubber wheels, the combination is out of the car; if we choose a wooden cart factory, using wooden cart parts is needed , it produced a wooden cart.

public static void main(String[] args) {
    // 使用小汽车工厂创建小汽车
    CarFactory f1 = new CompactCarFactory();
    Car compactCar = f1.createCar();
    System.out.println(compactCar.wheel.getClass());
    System.out.println(compactCar.window.getClass());

    // 使用木头车工厂创建木头车
    CarFactory f2 = new WoodenCarFactory();
    Car woodenCar = f2.createCar();
    System.out.println(woodenCar.wheel.getClass());
    System.out.println(woodenCar.window.getClass());
}

  Easy to see, in the abstract factory, the production process of each part, in fact, use the factory method pattern, and will put together these factory methods to produce a series of related objects, it becomes abstract factory. Let us abstract factory in the process of creating multiple objects associated with the use of their code decoupling, we do not care about the specific types of plants, because they are the type of their common parent class, we only need to call the parent class offered interfaces, polymorphism mechanism will operate correctly subclass. We do not need to care about what we produce is subject, because we are using a reference to their parent type, but does not affect the actual functionality. If we need to modify the objects of a factory, you only need to modify a factory method can be, and for the code that calls it, it will not have any effect, because the interface looks and returns the result did not change.


Third, the summary

  The main purpose of the factory pattern is to decouple the code to create an object using a logical object, it follows the guidelines for the programming interface, in fact, also followed the Dependency Inversion Principle. It is not only the factory mode, almost all of the design pattern, the effect is to reduce the coupling of the code to improve reusability of code.


Fourth, the reference

  • "Head First Design Patterns"

Guess you like

Origin www.cnblogs.com/tuyang1129/p/12595142.html