Summary of Design Pattern Learning-Factory Pattern

When we usually create objects, we use the keyword new to achieve, for example: Class A = new A().

In some cases, the object to be created requires a series of complex initialization operations, such as checking configuration files, checking database tables, initializing member objects, etc. If these logics are placed in the constructor, the readability of the code will be greatly affected . Might as well define a class to be responsible for the creation of objects. Such a class is a factory class. This approach is the factory pattern. The factory pattern can be used wherever complex objects need to be generated.

Factory patterns include: simple factories (not in the 23 design patterns), factory methods and abstract factories.

solved problem


The client does not want to judge which class to instantiate when calling or the instantiation process is too complicated.

In the factory model, the specific implementation class creation process is transparent to the client. The client does not decide which class to instantiate, but is handed over to the "factory" for instantiation.


Simple factory



▐  structure 

Define an interface for creating objects, and let its subclasses decide which factory class to instantiate.


  • Abstract class or interface: defines the interface of the product object to be created.

  • Specific realization: a specific type of product with a unified parent category.

  • Product factory: responsible for creating product objects. The factory model also embodies the principle of opening and closing, separating the changed code of "creating a specific product implementation class" from the unchanged code "using the product". Later, when you want to add new products, you only need to expand the implementation of the factory. That's it.

▐   use


Create keyboards of different brands

public interface Keyboard {
    void print();
    void input(Context context);
}


class HPKeyboard implements Keyboard {


    @Override
    public void print() {
        //...输出逻辑;
    }


    @Override
    public void input(Context context) {
        //...输入逻辑;
    }


}


class DellKeyboard implements Keyboard {


    @Override
    public void print() {
        //...输出逻辑;
    }


    @Override
    public void input(Context context) {
        //...输入逻辑;
    }


}


class LenovoKeyboard implements Keyboard {


    @Override
    public void print() {
        //...输出逻辑;
    }


    @Override
    public void input(Context context) {
        //...输入逻辑;
    }


}


/**
 * 工厂
 */
public class KeyboardFactory {
    public Keyboard getInstance(int brand) {
        if(BrandEnum.HP.getCode() == brand){
            return new HPKeyboard();
        } else if(BrandEnum.LENOVO.getCode() == brand){
            return new LenovoKeyboard();
        } else if(BrandEnum.DELL.getCode() == brand){
            return new DellKeyboard();
        }
        return null;
    }


    public static void main(String[] args) {
        KeyboardFactory keyboardFactory = new KeyboardFactory();
        Keyboard lenovoKeyboard = KeyboardFactory.getInstance(BrandEnum.LENOVO.getCode());
        //...
    }


}

▐  defect 

The above factory implementation is a concrete class KeyboardFactory, not an interface or abstract class. The getInstance() method uses if-else to create and return a concrete keyboard instance. If a new keyboard subclass is added, the keyboard factory creation method will Add new if-else. This approach has poor scalability, violates the principle of opening and closing, and also affects readability. Therefore, this method is used in situations where the business is simpler and the factory class does not change frequently.


Factory method


In order to solve the problem of "increase if-else" mentioned above, a corresponding factory subclass can be established for each keyboard subclass, and these factory subclasses implement the same abstract factory interface. In this way, to create keyboards of different brands, you only need to implement different factory subclasses. When a new brand is added, the new concrete factory inherits the abstract factory without modifying any class.

▐  structure 

  • Abstract factory: declares the interface of the factory method.

  • Specific product factory: implements the interface of the factory method and is responsible for creating product objects.

  • Product abstract class or interface: defines the interface of the product object created by the factory method.

  • Specific product realization: A specific type of product with a unified parent category.

▐  use 


public interface IKeyboardFactory {
    Keyboard getInstance();
}


public class HPKeyboardFactory implements IKeyboardFactory {
    @Override
    public Keyboard getInstance(){
        return new HPKeyboard();
    }
}


public class LenovoFactory implements IKeyboardFactory {
    @Override
    public Keyboard getInstance(){
        return new LenovoKeyboard();
    }
}


public class DellKeyboardFactory implements IKeyboardFactory {
    @Override
    public Keyboard getInstance(){
        return new DellKeyboard();
    }
}

▐  shortcomings 


Each brand corresponds to a factory subclass. When creating a specific keyboard object, instantiate different factory subclasses. However, if the business involves more and more sub-categories, does each sub-category correspond to a factory category? This will double the number of classes in the system and increase the complexity of the code.

Abstract factory


In order to reduce the number of sub-categories of the factory implementation, it is not necessary to assign a factory class to each product. Products can be grouped, and different products in each group are created by different methods of the same factory class.


For example, the two products of keyboard and host can be grouped into the same group-computers, and computers of different brands are created by different manufacturers.


Similar to this design pattern in which product categories are grouped, and different products in the group are implemented by different methods of the same factory category, it is the abstract factory pattern.


The abstract factory is suitable for the following situations:


1. When a system is to be independent of the creation, combination and presentation of its products;
2. When a system is to be configured by one of multiple product series;
3. To emphasize the design of a series of related product objects for joint When in use;
4. When you provide a product class library, but only want to display their interface instead of implementation;

▐  structure 

  • Abstract factory: declares the operation interface for creating abstract product objects.

  • Concrete product factory: It implements the abstract factory interface and is responsible for creating product objects.

  • Product abstract class or interface: defines the interface of a class of product objects.

  • Specific product realization: Define a product object that will be created by the corresponding specific factory.

▐  use 


public interface Keyboard {
   void print();
}
public class DellKeyboard implements Keyboard {
    @Override
    public void print() {
        //...dell...dell;
    }
}
public class HPKeyboard implements Keyboard {
    @Override
    public void print() {
        //...HP...HP;
    }
}
public interface Monitor {
   void play();
}
public class DellMonitor implements Monitor {
    @Override
    public void play() {
        //...dell...dell;
    }
}
public class HPMonitor implements Monitor {
    @Override
    public void play() {
        //...HP...HP;
    }
}
public interface MainFrame {
   void run();
}
public class DellMainFrame implements MainFrame {
    @Override
    public void run() {
        //...dell...dell;
    }
}
public class HPMainFrame implements MainFrame {
    @Override
    public void run() {
        //...HP...HP;
    }
}
//工厂类。工厂分为Dell工厂和HP工厂,各自负责品牌内产品的创建
public interface IFactory {
    MainFrame createMainFrame();
    Monitor createMainFrame();
    Keyboard createKeyboard();
}
public class DellFactory implements IFactory {
      @Override
      public MainFrame createMainFrame(){
                MainFrame mainFrame = new DellMainFrame();
             //...造一个Dell主机;
             return mainFrame;
      }


      @Override
      public Monitor createMonitor(){
                Monitor monitor = new DellMonitor();
             //...造一个Dell显示器;
             return monitor;
      }


      @Override
      public Keyboard createKeyboard(){
                Keyboard keyboard = new DellKeyboard();
             //...造一个Dell键盘;
             return Keyboard;
      }
}
public class HPFactory implements IFactory {
      @Override
      public MainFrame createMainFrame(){
                MainFrame mainFrame = new HPMainFrame();
             //...造一个HP主机;
             return mainFrame;
      }


      @Override
      public Monitor createMonitor(){
                Monitor monitor = new HPMonitor();
             //...造一个HP显示器;
             return monitor;
      }


      @Override
      public Keyboard createKeyboard(){
                Keyboard keyboard = new HPKeyboard();
             //...造一个HP键盘;
             return Keyboard;
      }
}
//客户端代码。实例化不同的工厂子类,可以通过不同的创建方法创建不同的产品
public class Main {
    public static void main(String[] args) {
        IFactory dellFactory = new DellFactory();
        IFactory HPFactory = new HPFactory();
        //创建戴尔键盘
        Keyboard dellKeyboard = dellFactory.createKeyboard();
        //...
    }
}

▐Pros  and cons 

Adding a group is very simple. For example, to add a Lenovo group, you only need to create a Lenovo factory and specific product implementation classes. It is very difficult to expand the products in the group. To add a mouse, it is necessary to create an abstract Mouse interface, but also to increase specific implementations: DellMouse, HPMouse, and define the method of creating a mouse in each Factory.

▐  summary 

  • Simple factory: a unique factory class, a product abstract class, the creation method of the factory class judges and creates specific product objects based on input parameters.

  • Factory method: multiple factory classes, one product abstract class, use polymorphism to create different product objects, avoiding a lot of if-else judgments.

  • Abstract factory: multiple factory classes, multiple product abstract classes, product subclasses grouping, the same factory implementation class creates different products in the same group, reducing the number of factory subclasses.

The factory model can be considered in the following situations:

  1. It is not possible to foresee which instance of the class needs to be created when coding.

  2. The system should not rely on the details of how product class instances are created, combined, and expressed.

In short, the factory pattern is to facilitate the creation of different objects with complex parameters and initialization steps defined by the same interface. The factory pattern is generally used to create complex objects. Simply use new to create successful simple objects, without using the factory pattern, otherwise it will increase the complexity of the system.


In addition, if the parameters of the object are not fixed, it is recommended to use the Builder mode.


postscript


In actual projects, combined with the InitializingBean interface in Spring, you can use the @Autowired annotation to elegantly implement the factory.

Tao Department Technical Department-Industry Technical Team-Recruiting Talents

We are the Alibaba Taoist industry technical team responsible for the growth and innovation of the Taoist industry’s e-commerce business. We support the rapid development of dozens of industries such as apparel, FMCG, home improvement, and power consumption. We serve tens of millions of users every day and generate thousands of 100 million GMV. Here, you can get in touch with the core business and technical system of the entire Taobao industry, empower multiple Taobao Tmall industries, and quickly incubate innovative businesses; here, you can also dig deeper into industry commercialization and distribution scenarios to activate the industry Various ecological roles create new growth in e-commerce business.

Recruitment position: java development

If you are interested, please send your resume to [email protected] , welcome to pick up~

✿ Further   reading

Author | Fang Hui (Huaixing)

Edit| Orange

Produced| Alibaba's new retail technology

Guess you like

Origin blog.csdn.net/Taobaojishu/article/details/110508149