“This is the 27th day of my participation in the Gwen Challenge in November. See details of the event: The Last Gwen Challenge in 2021”

Factory method pattern

The simple factory pattern introduced last time has some drawbacks.

The factory method pattern is a further abstraction of the simple factory pattern, which meets the open and closed principle and enables the system to introduce new products without changing the original code. The factory method pattern introduces the factory hierarchy structure to solve the problem of the excessive responsibility of the factory class in the simple factory pattern

Factory method pattern: By defining a factory’s parent class (responsible for defining the common interface to create objects)

The factory method pattern postpones class instantiation to subclasses. The factory class is not responsible for the creation of all products. When adding a new product to the interface of the corresponding implementation, there is no need to modify the logic of the factory class, just add a new factory subclass.

implementation

Abstract factory class, which defines the public interface for a concrete factory through which the caller creates the product by accessing the factory method getProduct() for the concrete factory.

abstract class AbstractFactory {
    abstract Product getProduct(a);
}
Copy the code

Abstract product classes define the common interfaces of a specific product and describe the main features and functions of the product.

abstract class Tea {
    public abstract void makeTea(a);
}
Copy the code

Concrete product classes, which inherit the concrete products produced by the abstract product class definition

Public class BlackTea extends Tea {@override public void makeProduct() {system.out.println (" make a pot of Tea "); }} public class extends Product {@override public void makeProduct() {system.out.println (" make a pot of tea "); }}Copy the code

The concrete factory class inherits the abstract factory class to create concrete products

public class BlackTeaFactory extends AbstractFactory {
    public Tea getProduct(a) {
        return newBlackTea(); }}public class GreenTeaFactory extends AbstractFactory {
    public Tea getProduct(a) {
        return newGreenTea(); }}Copy the code

conclusion

advantages

  • This implementation is more in line with the open closed principle. If a new product is added, it only needs to add the corresponding specific product and the corresponding factory subclass.
  • Each factory is only responsible for the production of corresponding products, in line with the principle of single responsibility.
  • No static methods are used, resulting in a hierarchical structure that can be inherited.

disadvantages

  • It is easy to have too many classes and add complexity
  • Abstract factory model can solve the problem that a concrete factory can only produce one kind of product.