Design pattern - factory pattern (including: simple factory pattern, factory method pattern, abstract factory pattern)

 Related Links:

[Design Pattern] Column: [Design Pattern] Column

Relevant sample codes can be downloaded:  Examples of common design patterns in Java

Introduction

At present, the factory mode is roughly divided into three types, namely:

  1. Simple Factory Pattern

  2. factory method pattern

  3. abstract factory pattern

Simple Factory Pattern

The Simple Factory Pattern (Simple Factory Pattern) is a creational pattern , also known as the Static Factory Method (Static Factory Method Pattern) pattern , but it does not belong to one of the 23 GOF design patterns. The simple factory pattern is to determine which instance of a product class to create by a factory object. The simple factory pattern is the simplest and most practical pattern in the factory pattern family, which can be understood as a special implementation of different factory patterns.

effect:

Separate the "class instantiation" operation from the "use object" operation, so that users can instantiate the required "product" class without knowing the specific parameters, thus avoiding explicit specification in the client code and realizing Decoupling.

main character

Specific factory (Creator) role

The core of the simple factory pattern, which is responsible for implementing the internal logic of creating all instances. The method of creating a product class in the factory class can be directly called by the outside world to create the required product object.

Abstract Product role

The parent class of all objects created by the simple factory pattern, which is responsible for describing the public interface shared by all instances.

Concrete Product role

The creation goal of the simple factory pattern, all created objects are instances of a specific class that plays this role.

 

Take a chestnut:

Suppose there is a beverage machine (factory) that can call out beverages of various flavors (abstract products), and there are three buttons (parameters) corresponding to these three beverages (concrete products). At this time, you can choose your favorite drink by clicking the button.

Abstract Product : Product.java

/**
 * 简单工厂模式——抽象产品
 * 说明:
 * 描述产品的公共接口
 *
 */
public abstract class Product {
    /**
     * 产品介绍
     */
    public abstract void introduce();
}

Specific products : CocoProduct.java, MilkProduct.java, CofficeProduct.java

/**
 * 简单工厂模式——具体产品 A
 *
 * (可以看成是一种饮料:可乐)
 *
 */
public class CocoProduct extends Product{

    @Override
    public void introduce() {
        System.out.println("可乐");
    }
}


/**
 * 简单工厂模式——具体产品 B
 *
 *(可以看成是一种饮料:奶茶)
 *
 */
public class MilkProduct extends Product{

    @Override
    public void introduce() {
        System.out.println("奶茶");
    }
}


/**
 * 简单工厂模式——具体产品 C
 *
 * (可以看成是一种饮料:咖啡)
 *
 */
public class CofficeProduct extends Product{

    @Override
    public void introduce() {
        System.out.println("咖啡");
    }
}

Concrete factory : SimpleFactory.java

/**
 * 简单工厂模式——具体工厂
 * 
 * 负责实现创建所有实例的内部逻辑,并提供一个外接调用的方法,创建所需的产品对象
 *
 */
public class SimpleFactory {

    /**
     * 提供给外接调用的方法
     * (可以看成是对外提供的三个小按钮)
     *
     * @param type 产品类型
     * @return FactoryPattern.SimpleFactoryPattern.Product
     */
    public static Product getProduct(String type) {
        switch (type) {
            case "coco":
                return new CocoProduct();
            case "milk":
                return new MilkProduct();
            case "coffice":
                return new CofficeProduct();
            default:
                return null;
        }
    }

}

Test: SimpleFactoryDemo.java

/**
 * 简单工厂模式
 *
 */
public class SimpleFactoryDemo {

    public static void main(String[] args) {
        // 创建具体的工厂
        SimpleFactory factory = new SimpleFactory();
        // 根据传入的参数生产不同的产品实例
        // (按下不同的按钮,获取饮料)
        Product coco = SimpleFactory.getProduct("coco");
        coco.introduce();
        Product milk = SimpleFactory.getProduct("milk");
        milk.introduce();
        Product coffice = SimpleFactory.getProduct("coffice");
        coffice.introduce();
    }

}

 

According to chestnuts can be described as:

  • An abstract product class can derive multiple concrete product classes

  • A specific factory class, by staticpassing in different parameters to the method of this factory, different specific product class instances are produced

Advantages and disadvantages

advantage

  • Separate the creation and use work, don't care about how the class object is created, and achieve decoupling

  • Putting the work of initializing the instance into the factory makes the code easier to maintain. More in line with object-oriented principles & interface-oriented programming, rather than implementation-oriented programming

shortcoming

  • The factory class concentrates the creation logic of all instances (products). Once the factory fails to work properly, the entire system will be affected

  • Violating the "open-close" principle, once a new product is added, the logic of the factory class has to be modified, which will cause the factory logic to be too complicated

  • The simple factory pattern uses static factory methods, and static methods cannot be inherited and rewritten, which will cause factory roles to fail to form

factory method pattern

The factory method pattern, also known as the factory pattern (Factory Pattern) , polymorphic factory pattern and virtual constructor pattern, is responsible for defining the public interface for creating objects by defining the factory parent class, while the subclass is responsible for generating specific objects. (commonly used!)

effect:

The instantiation of the class (creation of specific products) is delayed to the subclass of the factory class (concrete factory), that is, the subclass decides which class should be instantiated (created).

main character

Abstract Factory role

Describes the public interface of a concrete factory.

Concrete Factory role

Describe the specific factory, create an instance of the product for external calls, mainly realize the abstract method in the abstract factory, and complete the creation of the specific product.

Abstract Product role

Responsible for describing the public interface of the product, defining the specification of the product, and describing the main features and functions of the product.

Concrete Product role

It describes the specific products produced, implements the interface defined by the abstract product role, and is created by the specific factory, which corresponds to the specific factory one by one.

 

Take a chestnut:

Assuming that there are various beverage machines (abstract factories), various beverages (abstract products) can be called out. However, a type of beverage machine (specific factory) can only produce one type of beverage (specific product). If you need to drink Coke, you need to buy a Coke beverage machine.

Abstract Product : Product.java

/**
 * 工厂方法模式——抽象产品
 *
 */
public abstract class Product {
    /**
     * 产品介绍
     */
    public abstract void introduce();
}

Specific products : ProductA.java, ProductB.java

/**
 * 工厂方法模式——具体产品A
 *
 */
public class ProductA extends Product{
    @Override
    public void introduce() {
        System.out.println("饮料A");
    }
}


/**
 * 工厂方法模式——具体产品B
 *
 */
public class ProductB extends Product{
    @Override
    public void introduce() {
        System.out.println("饮料B");
    }
}

Abstract factory : Factory.java

/**
 * 工厂方法模式——抽象工厂
 *
 */
public abstract class Factory {
    /**
     * 生产产品
     *
     * @return FactoryPattern.FactoryPattern.Product
     */
    public abstract Product getProduct();
}

Specific factories : FactoryA.java, FactoryB.java

/**
 * 工厂方法模式——具体工厂A
 *
 * (负责具体的产品A生产)
 *
 */
public class FactoryA extends Factory{
    @Override
    public Product getProduct() {
        return new ProductA();
    }
}


/**
 * 工厂方法模式——具体工厂B
 *
 * (负责具体的产品B生产)
 *
 */
public class FactoryB extends Factory{
    @Override
    public Product getProduct() {
        return new ProductB();
    }
}

Test : FactoryDemo.java

/**
 * 工厂方法模式
 *
 */
public class FactoryDemo {

    public static void main(String[] args) {
        // 创建具体的工厂
        FactoryA factoryA = new FactoryA();
        // 生产相对应的产品
        factoryA.getProduct().introduce();
        FactoryB factoryB = new FactoryB();
        factoryB.getProduct().introduce();
    }

}

 

According to chestnuts can be described as

  • An abstract product class can derive multiple concrete product classes

  • An abstract factory class that can derive multiple concrete factory classes

  • Each concrete factory class can only create an instance of a concrete product class

Advantages and disadvantages

advantage

  • Comply with the "open-close principle" and have high scalability: when adding a new product, you only need to add the corresponding specific product category and the corresponding factory subcategory

  • Comply with the principle of single responsibility: each specific factory class is only responsible for creating corresponding products

shortcoming

  • Increased system complexity: the number of classes will increase in pairs

  • Increased abstraction and difficulty of understanding the system

  • A specific factory can only create a specific product

abstract factory pattern

Abstract Factory Pattern (Abstract Factory Pattern) is to create other factories around a super factory. The super factory is also known as the factory of other factories. This type of design pattern is a creational pattern, which provides an optimal way to create objects.

In the Abstract Factory pattern, interfaces are factories responsible for creating a related object without specifying their class explicitly. Each generated factory can provide objects according to the factory pattern.

The biggest difference between the abstract factory pattern and the factory method pattern :

  • In an abstract factory, each factory can create multiple types of products
  • In the factory method, each factory can only create one type of product

effect

Allows the use of abstract interfaces to create a set of related products without knowing or caring what the actual concrete product is, so that it can be decoupled from the concrete product.

main character

Abstract Factory role

Describes the public interface of a concrete factory

Concrete Factory role

Describe the specific factory and create an instance of the product for external calls

Abstract Product Family (Abstract Product) role

Describes the public interface of the abstract product

Abstract Product role

Describe the public interface of a specific product

Concrete Product role

Describe the specific product produced

 

Take a chestnut:

Suppose there are various types of vending machines (abstract factories) that can sell various types of food (abstract product families).

There are beverages and snacks (abstract products), such as common retail vending machines (concrete factories), selling mineral water and bread (concrete products).

Abstract product family : Product.java

/**
 * 抽象工厂模式——抽象产品族(食品)
 *
 */
public abstract class Product {
    /**
     * 产品介绍
     */
    public abstract void introduce();
}

Abstract product : ProductA.java, ProductB.java

/**
 * 抽象工厂模式——抽象产品(饮料)
 *
 */
public abstract class ProductA extends Product{
}


/**
 * 抽象工厂模式——抽象产品(零食)
 *
 */
public abstract class ProductB extends Product{
}

Specific products : ProductAa.java, ProductBb.java

/**
 * 抽象工厂模式——具体产品
 *
 */
public class ProductAa extends ProductA{
    @Override
    public void introduce() {
        System.out.println("矿泉水");
    }
}


/**
 * 抽象工厂模式——具体产品
 *
 */
public class ProductBb extends ProductB{
    @Override
    public void introduce() {
        System.out.println("面包");
    }
}

Abstract factory : AbstractFactory.java

/**
 * 抽象工厂模式——抽象工厂
 *
 */
public abstract class AbstractFactory {
    /**
     * 生产饮料
     */
    public abstract Product getProductA();
    /**
     * 生产零食
     */
    public abstract Product getProductB();
}

Specific factory : AbstractFactoryA.java

/**
 * 抽象工厂模式——具体工厂
 *
 * 负责具体的A类产品生产
 *
 */
public class AbstractFactoryA extends AbstractFactory{
    @Override
    public Product getProductA() {
        // 生产矿泉水
        return new ProductAa();
    }

    @Override
    public Product getProductB() {
        // 生产面包
        return new ProductBb();
    }
}

Test : AbstractFactoryDemo.java

/**
 * 抽象工厂模式
 *
 */
public class AbstractFactoryDemo {

    public static void main(String[] args) {
        // 创建零食售卖机(具体工厂)
        AbstractFactoryA abstractFactoryA = new AbstractFactoryA();
        // 获取矿泉水与面包(具体产品)
        abstractFactoryA.getProductA().introduce();
        abstractFactoryA.getProductB().introduce();
    }

}

 

According to examples, it can be described as:

  • Multiple abstract product classes, each abstract product can derive multiple concrete product classes

  • An abstract factory class that can derive multiple concrete factory classes

  • Each specific factory class can create multiple instances of specific product classes

Advantages and disadvantages

advantage

  • reduce coupling

  • Complies with the "open-closed principle"

  • Complies with the Single Responsibility Principle

  • Instead of using static factory methods, an inheritance-based hierarchical structure can be formed

  • When multiple objects in a product family are designed to work together, it guarantees that clients always use only objects from the same product family.

shortcoming

  • It is difficult to expand new types of products. To add a certain product in a series, it is necessary to add code to the abstract product and add code to the specific one.

conclusion

1. For more design patterns, please see the [Design Patterns] column

2. Relevant sample codes can be downloaded:  Examples of common design patterns in Java

PS: [  Example of common design patterns  in Java] has included  the code involved in the [Design Pattern] column  . If you have downloaded it before, you don’t need to download it again~

If the above content is incorrect or needs to be supplemented, please ask for more advice, and it will be updated and corrected in time~

Comments are welcome~ Thank you for your praise~

Guess you like

Origin blog.csdn.net/pjymyself/article/details/121931718