Detailed explanation of factory mode of design mode

Classification of patterns

The creation pattern provides a mechanism for creating objects, which can improve flexibility and the importance of existing code

The structure pattern explains that objects and classes assemble a larger structure while maintaining the flexibility and efficiency of the structure

The behavior model is responsible for the communication between each other and the effective allocation of responsibilities among the objects

Factory mode

If the factory mode, such as logistics business, is limited to truck transportation, then directly develop the truck interface, only use the truck class, and then add the ship transportation, the coupling will be very large, and the code change will be very troublesome. So we need to use factory mode


If both ships and trucks need to use the Transport class, and the Transport interface has a delivery () delivery method, the truck Transport and delivery, the ship Transport and delivery, and return different objects, which is simple and clear

In such a flow chart, the factory method is called, which is referred to as the code of the client for short. There is no need to understand the differences of various return objects. The client collectively refers to all Transport interface products as abstract classes (Abstract transportation). The client knows that all transportation methods have delivery methods, but does not care about the specific implementation methods.


1. For product interface, the interface will be declared. For all creators and subclasses, the interface is completely universal
2.ConcreteProduct is the realization of different product interfaces
3.Creator is a creator class, but it is a factory method that declares and returns the product object. The method type must match the method of the product interface, that is, separate the different implementations of the product interface. Factory methods can be declared as abstract methods, forcing each different class to implement the method in a different way.

The factory method pattern is suitable for application scenarios

1.If you cannot know the exact category of the object and its dependencies, you can use the factory method.

2.The factory method separates the code of the created product from the product code actually used, so that the code of the created part of the product can not be extended without affecting other codes.

3.If you want to add a new product, you just need to develop a new subclass and rewrite the factory method.

4.If users want to extend the components of the software library or framework, they can use the factory method.

	4.1 For example, you need to use an open source UI You need to use the rectangle button to write the standard button, but you need to use the rectangle button UI frame UIFramework Class uses a new subclass button instead of the default button.

		In order to realize the function, you can use the circular button according to the subclass of the basic framework class UIWithRoundButtons´╝îAnd override the button creation method to return the button object in the basic class. Now the newly developed object can be replaced by a new circular button class ui Framework class.

5.If you want to reuse existing objects to save system resources instead of recreating objects every time, you can use the factory method.

Advantages and disadvantages of factory mode

It can avoid the close coupling between the creator and specific products.
With a single responsibility, the product creation code can be placed in a single setting of the program, which is easier to maintain.
According to the opening and closing principle, new specific product types can be developed without changing the code of the existing client.
Disadvantages: the factory pattern needs to introduce many new subclasses, and the code will become complex. The best case is to introduce the pattern into the existing hierarchy of the creator class.

Relationship with other modes

1. In many designs, factory mode is relatively simple, and then evolved into abstract factory mode. Prototype mode or generator mode is more flexible but more complex.
2. The abstract factory pattern is based on a set of factory patterns. You can also use the prototype pattern to generate the methods of these classes.
3. You can use factory mode and iterator mode to make the subclass collection return iterators of different types and match the iterator with the collection.
4. The prototype mode is not based on inheritance, so there is no disadvantage of inheritance, but the prototype mode needs complex initialization, and the factory mode is based on inheritance, so it does not need initialization.
5. Factory mode is a special form of template method mode. At the same time, factory mode can be used as a step in a large template method.

Code example

buttons/Button.java: general product interface

package refactoring_guru.factory_method.example.buttons;

/**
 * Common interface for all buttons.
 */
public interface Button {
    void render();
    void onClick();
}

buttons/HtmlButton.java: specific products

package refactoring_guru.factory_method.example.buttons;

/**
 * HTML button implementation.
 */
public class HtmlButton implements Button {

    public void render() {
        System.out.println("<button>Test Button</button>");
        onClick();
    }

    public void onClick() {
        System.out.println("Click! Button says - 'Hello World!'");
    }
}

buttons/WindowsButton.java: another specific product

package refactoring_guru.factory_method.example.buttons;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Windows button implementation.
 */
public class WindowsButton implements Button {
    JPanel panel = new JPanel();
    JFrame frame = new JFrame();
    JButton button;

    public void render() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel label = new JLabel("Hello World!");
        label.setOpaque(true);
        label.setBackground(new Color(235, 233, 126));
        label.setFont(new Font("Dialog", Font.BOLD, 44));
        label.setHorizontalAlignment(SwingConstants.CENTER);
        panel.setLayout(new FlowLayout(FlowLayout.CENTER));
        frame.getContentPane().add(panel);
        panel.add(label);
        onClick();
        panel.add(button);

        frame.setSize(320, 200);
        frame.setVisible(true);
        onClick();
    }

    public void onClick() {
        button = new JButton("Exit");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                frame.setVisible(false);
                System.exit(0);
            }
        });
    }
}

factory/Dialog.java: Foundation Creator

package refactoring_guru.factory_method.example.factory;

import refactoring_guru.factory_method.example.buttons.Button;

/**
 * Base factory class. Note that "factory" is merely a role for the class. It
 * should have some core business logic which needs different products to be
 * created.
 */
public abstract class Dialog {

    public void renderWindow() {
        // ... other code ...

        Button okButton = createButton();
        okButton.render();
    }

    /**
     * Subclasses will override this method in order to create specific button
     * objects.
     */
    public abstract Button createButton();
}

factory/HtmlDialog.java: specific Creator

package refactoring_guru.factory_method.example.factory;

import refactoring_guru.factory_method.example.buttons.Button;
import refactoring_guru.factory_method.example.buttons.HtmlButton;

/**
 * HTML Dialog will produce HTML buttons.
 */
public class HtmlDialog extends Dialog {

    @Override
    public Button createButton() {
        return new HtmlButton();
    }
}

factory/WindowsDialog.java: another specific Creator

package refactoring_guru.factory_method.example.factory;

import refactoring_guru.factory_method.example.buttons.Button;
import refactoring_guru.factory_method.example.buttons.WindowsButton;

/**
 * Windows Dialog will produce Windows buttons.
 */
public class WindowsDialog extends Dialog {

    @Override
    public Button createButton() {
        return new WindowsButton();
    }
}

Demo.java: client code

package refactoring_guru.factory_method.example;

import refactoring_guru.factory_method.example.factory.Dialog;
import refactoring_guru.factory_method.example.factory.HtmlDialog;
import refactoring_guru.factory_method.example.factory.WindowsDialog;

/**
 * Demo class. Everything comes together here.
 */
public class Demo {
    private static Dialog dialog;

    public static void main(String[] args) {
        configure();
        runBusinessLogic();
    }

    /**
     * The concrete factory is usually chosen depending on configuration or
     * environment options.
     */
    static void configure() {
        if (System.getProperty("os.name").equals("Windows 10")) {
            dialog = new WindowsDialog();
        } else {
            dialog = new HtmlDialog();
        }
    }

    /**
     * All of the client code should work with factories and products through
     * abstract interfaces. This way it does not care which factory it works
     * with and what kind of product it returns.
     */
    static void runBusinessLogic() {
        dialog.renderWindow();
    }
}

OutputDemo.txt: execution result (Html) ­ Dialog)

<button>Test Button</button>
Click! Button says - 'Hello World!'

OutputDemo.png: execution result (Windows) ­ Dialog)

Just finished learning, share your experience, and make a record of yourself. Come on together. Here is amhersh who can't write code.

Tags: Java Design Pattern interface

Posted by gardnc on Tue, 17 May 2022 14:26:51 +0300