Design pattern factory pattern (including simple factory pattern, factory method pattern and abstract factory pattern)

Posted by scotchegg78 on Thu, 16 Dec 2021 15:52:02 +0100

Related links:

[design mode] column: [design mode] column

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

brief introduction

At present, there are three factory modes, namely:

  1. Simple factory mode

  2. Factory method model

  3. Abstract factory pattern

Simple factory mode

Simple Factory Pattern is a creation pattern, also known as 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 an instance of which product class is created 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:

The "class instantiation" operation is separated from the "use object" operation, so that the user can instantiate the required "product" class without knowing the specific parameters, so as to avoid explicit specification in the client code and realize decoupling.

Main role

Specific factory (Creator) role

The core of the simple factory pattern, which is responsible for implementing the internal logic for creating all instances. The method of creating product class of 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 common interface shared by all instances.

Concrete Product role

The creation target of the simple factory pattern. All created objects are instances of a specific class that plays this role.

 

For example, chestnuts:

Suppose there is a beverage machine (factory) that can call up drinks of various flavors (Abstract products), and there are three buttons (parameters) corresponding to these three drinks (specific products). At this time, you can click the button to select your favorite drinks.

Abstract product: product java

/**
 * Simple factory pattern - abstract product
 * explain:
 * Describe the common interface of the product
 *
 */
public abstract class Product {
    /**
     * Product introduction
     */
    public abstract void introduce();
}

Specific product: cocoproduct java  , MilkProduct.java , CofficeProduct.java

/**
 * Simple factory model - specific product A
 *
 * (It can be regarded as a kind of beverage: coke)
 *
 */
public class CocoProduct extends Product{

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


/**
 * Simple factory model - specific product B
 *
 *(It can be regarded as a drink: milk tea)
 *
 */
public class MilkProduct extends Product{

    @Override
    public void introduce() {
        System.out.println("tea with milk");
    }
}


/**
 * Simple factory model - specific product C
 *
 * (Can be regarded as a drink: coffee)
 *
 */
public class CofficeProduct extends Product{

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

Specific factory: simplefactory java

/**
 * Simple factory model - specific factory
 * 
 * It is responsible for implementing the internal logic of creating all instances, and providing an external call method to create the required product objects
 *
 */
public class SimpleFactory {

    /**
     * Methods provided to external calls
     * (It can be regarded as three small buttons provided externally)
     *
     * @param type product 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

/**
 * Simple factory mode
 *
 */
public class SimpleFactoryDemo {

    public static void main(String[] args) {
        // Create specific factories
        SimpleFactory factory = new SimpleFactory();
        // Produce different product instances according to the passed parameters
        // (press different buttons to get drinks)
        Product coco = SimpleFactory.getProduct("coco");
        coco.introduce();
        Product milk = SimpleFactory.getProduct("milk");
        milk.introduce();
        Product coffice = SimpleFactory.getProduct("coffice");
        coffice.introduce();
    }

}

 

According to chestnut, it can be described as:

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

  • A specific factory class that outputs different specific product class instances by passing different parameters into the static method of the factory

Advantages and disadvantages

advantage

  • The creation and use work are separated, and there is no need to care about how to create class objects, which realizes decoupling

  • Put the work of initializing the instance into the factory to make the code easier to maintain. More in line with the principle of object-oriented & Interface oriented programming, rather than implementation oriented programming

shortcoming

  • The factory class centralizes the creation logic of all instances (products). Once the factory fails to work normally, the whole system will be affected

  • Contrary to the "open close" principle, once a new product is added, the logic of the factory class will have to be modified, which will cause the factory logic to be too complex

  • The simple factory mode uses static factory methods, which cannot be inherited and overridden, resulting in the failure to form factory roles

Factory method model

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

effect:

The instantiation of a class (creation of a specific product) is delayed to the subclass of the factory class (specific factory), that is, the subclass determines which class should be instantiated (created).

Main role

Abstract Factory role

Describe the common interface of the specific plant.

Concrete Factory role

Describe the specific factory and create product instances for external calls. It mainly implements the abstract methods in the abstract factory to complete the creation of specific products.

Abstract Product role

It is responsible for describing the public interface of the product, defining the product specification, and describing the main characteristics 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.

 

For example, chestnuts:

Suppose there are all kinds of beverage machines (Abstract factories), which can call out all kinds of drinks (Abstract products). However, a kind of beverage machine (specific factories) can only produce one kind of beverage (specific products). If you need to drink coke, you need to buy Coke beverage machines.

Abstract product: product java

/**
 * Factory method pattern - abstract product
 *
 */
public abstract class Product {
    /**
     * Product introduction
     */
    public abstract void introduce();
}

Specific product: ProductA java ,ProductB.java

/**
 * Factory method model - specific product A
 *
 */
public class ProductA extends Product{
    @Override
    public void introduce() {
        System.out.println("Drinks A");
    }
}


/**
 * Factory method model - specific product B
 *
 */
public class ProductB extends Product{
    @Override
    public void introduce() {
        System.out.println("Drinks B");
    }
}

Abstract factory: factory java

/**
 * Factory method pattern -- Abstract Factory
 *
 */
public abstract class Factory {
    /**
     * yield a product
     *
     * @return FactoryPattern.FactoryPattern.Product
     */
    public abstract Product getProduct();
}

Specific factory: FactoryA java ,FactoryB.java

/**
 * Plant approach model - specific plant A
 *
 * (Responsible for specific product A production)
 *
 */
public class FactoryA extends Factory{
    @Override
    public Product getProduct() {
        return new ProductA();
    }
}


/**
 * Plant approach model - specific plant B
 *
 * (Responsible for specific product B production)
 *
 */
public class FactoryB extends Factory{
    @Override
    public Product getProduct() {
        return new ProductB();
    }
}

Testing: factorydemo java

/**
 * Factory method model
 *
 */
public class FactoryDemo {

    public static void main(String[] args) {
        // Create specific factories
        FactoryA factoryA = new FactoryA();
        // Produce corresponding products
        factoryA.getProduct().introduce();
        FactoryB factoryB = new FactoryB();
        factoryB.getProduct().introduce();
    }

}

 

According to chestnuts can be described as

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

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

  • Each specific factory class can only create one instance of a specific product class

Advantages and disadvantages

advantage

  • It conforms to the "open close principle" and has high expansibility: when adding a new product, you only need to add the corresponding specific product category and corresponding factory subclass

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

shortcoming

  • The complexity of the system is increased: the number of classes will increase in pairs

  • It increases the abstraction and understanding difficulty of the system

  • A specific factory can only create one specific product

Abstract factory pattern

Abstract Factory Pattern is to create other factories around a super factory. This super factory is also called the factory of other factories. This type of design pattern belongs to creation mode, which provides the best way to create objects.

In the abstract factory pattern, an interface is a factory responsible for creating a related object, and there is no need to explicitly specify their classes. Each generated factory can provide objects according to the factory pattern.

The biggest difference between abstract factory mode and factory method mode:

  • In the abstract factory, each factory can create many kinds of products
  • In the factory method, each factory can only create one type of product

effect

It allows the use of abstract interfaces to create a set of related products without knowing or caring about the actual production of specific products, so that they can be decoupled from specific products.

Main role

Abstract Factory role

Describe the common interface of the specific plant

Concrete Factory role

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

Abstract Product role

Describes the common interface of the abstract product

Abstract Product role

Describe the common interface of specific products

Concrete Product role

Describe the specific products produced

 

For example, chestnuts:

Suppose there are all kinds of vending machines (Abstract factories) that can sell all kinds of food (abstract product family).

There are drinks and snacks (Abstract products), such as common retail vending machines (specific factories) and mineral water and bread (specific products).

Abstract product family: product java

/**
 * Abstract factory pattern - abstract product family (food)
 *
 */
public abstract class Product {
    /**
     * Product introduction
     */
    public abstract void introduce();
}

Abstract product: ProductA java,ProductB.java

/**
 * Abstract factory pattern - abstract product (beverage)
 *
 */
public abstract class ProductA extends Product{
}


/**
 * Abstract factory pattern - Abstract products (snacks)
 *
 */
public abstract class ProductB extends Product{
}

Specific product: productaa java,ProductBb.java

/**
 * Abstract factory pattern - concrete product
 *
 */
public class ProductAa extends ProductA{
    @Override
    public void introduce() {
        System.out.println("mineral water");
    }
}


/**
 * Abstract factory pattern - concrete product
 *
 */
public class ProductBb extends ProductB{
    @Override
    public void introduce() {
        System.out.println("bread");
    }
}

Abstract factory: AbstractFactory java

/**
 * Abstract factory pattern - Abstract Factory
 *
 */
public abstract class AbstractFactory {
    /**
     * Production of beverages
     */
    public abstract Product getProductA();
    /**
     * Produce snacks
     */
    public abstract Product getProductB();
}

Specific factory: abstractfactorya java

/**
 * Abstract factory pattern - concrete factory
 *
 * Responsible for the production of specific class A products
 *
 */
public class AbstractFactoryA extends AbstractFactory{
    @Override
    public Product getProductA() {
        // Production of mineral water
        return new ProductAa();
    }

    @Override
    public Product getProductB() {
        // Production of bread
        return new ProductBb();
    }
}

Test: abstractfactorydemo java

/**
 * Abstract factory pattern
 *
 */
public class AbstractFactoryDemo {

    public static void main(String[] args) {
        // Create a snack vending machine (specific factory)
        AbstractFactoryA abstractFactoryA = new AbstractFactoryA();
        // Access to mineral water and bread (specific products)
        abstractFactoryA.getProductA().introduce();
        abstractFactoryA.getProductB().introduce();
    }

}

 

According to the example, it can be described as:

  • Multiple abstract product classes, and 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

  • Comply with the "open close principle"

  • Consistent with the principle of single responsibility

  • Without using the static factory method, an inheritance based hierarchical structure can be formed

  • When multiple objects in a product family are designed to work together, it can ensure that the client always uses only the objects in the same product family.

shortcoming

  • It is difficult to expand new types of products. To add a series of products, we should add code not only in the abstract products, but also in the concrete products.

Conclusion

1. See more about design patterns [design mode] column

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

PS:   [ Examples of common Java design patterns Included in] [design mode] column If you have downloaded the code previously, you don't need to download it again~

If the above contents are incorrect or need to be supplemented, please consult more and update and correct them in time~

Welcome to comment ~ thank you for your praise~

Topics: Java Design Pattern