(Design Pattern) Factory Pattern

factory pattern

Factory pattern (Factory Pattern) is one of the most commonly used design patterns in Java. This type of design pattern is a creational pattern , which provides an optimal way to create objects.

In the factory mode, we do not expose the creation logic to the client when creating an object, and use a common interface to point to the newly created object.

introduce

**Intention:** Define an interface for creating objects, let its subclasses decide which factory class to instantiate, and the factory mode delays the creation process to subclasses.

** Main solution: ** Mainly solve the problem of interface selection.

**When to use:** When we explicitly plan to create different instances under different conditions.

**How ​​to solve:** Let its subclass implement the factory interface, and return an abstract product.

**Key code:** The creation process is executed in its subclasses.

Application examples: 1. You need a car, you can pick up the goods directly from the factory, regardless of how the car is made and the specific realization of the car. 2. To change the database in Hibernate, you only need to change the dialect and driver.

Advantages: 1. If a caller wants to create an object, he only needs to know its name. 2. High scalability. If you want to add a product, you only need to extend a factory class. 3. Shield the specific implementation of the product, and the caller only cares about the interface of the product.

**Disadvantages:** Every time a product is added, it is necessary to add a specific class and object implementation factory, which doubles the number of classes in the system, increases the complexity of the system to a certain extent, and also increases the System concrete class dependencies. This is not a good thing.

Usage scenarios: 1. Log recorder: The records may be recorded to the local hard disk, system events, remote servers, etc., and the user can choose where to record the logs. 2. Database access, when the user does not know which type of database the system uses in the end, and the database may change. 3. To design a framework for connecting to the server, three protocols are required, "POP3", "IMAP", and "HTTP". These three can be used as product categories to jointly implement an interface.

**Notes:** As a class creation pattern, the factory method pattern can be used wherever complex objects need to be generated. One thing to note is that complex objects are suitable for using the factory pattern, while simple objects, especially objects that only need to be created through new, do not need to use the factory pattern. If you use the factory pattern, you need to introduce a factory class, which will increase the complexity of the system.

accomplish

We will create a Shape interface and entity classes implementing the Shape interface. The next step is to define the factory class ShapeFactory .

The FactoryPatternDemo class uses ShapeFactory to obtain Shape objects. It will pass information ( CIRCLE / RECTANGLE / SQUARE ) to the ShapeFactory in order to get the type of object it needs.

UML diagram of factory pattern

step 1

Create an interface:

Shape.java

/**
 * 步骤1:创建一个接口
 */
public interface Shape {
    
    
    void draw();
}

step 2

Create an entity class that implements the interface.

Rectangle.java

/**
 * 步骤2:创建接口的实体类
 */
public class Rectangle implements Shape{
    
    
    @Override
    public void draw() {
    
    
        System.out.println( "Inside Rectangle :: draw() method." );
    }
}

Square.java

/**
 * 步骤2:创建接口的实体类
 */
public class Square implements Shape {
    
    
    @Override
    public void draw() {
    
    
        System.out.println("Inside Square::draw() method.");
    }
}

Circle.java

/**
 * 步骤2:创建接口的实体类
 */
public class Circle implements Shape {
    
    
    @Override
    public void draw() {
    
    
        System.out.println("Inside Circle::draw() method.");
    }
}

step 3

Create a factory that produces objects of entity classes based on given information.

ShapeFactory.java

/**
 * 步骤3:创建一个工厂,生成基于给定信息的实体类的对象
 */
public class ShapeFactory {
    
    
    /**
     * 使用 getShape 方法获取类型的对象
     */
    public Shape getShape(String shapeType) {
    
    
        if (shapeType == null) {
    
    
            return null;
        }
        if (shapeType.equalsIgnoreCase("CIRCLE")) {
    
    
            return new Circle();
        } else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
    
    
            return new Rectangle();
        } else if(shapeType.equalsIgnoreCase("SQUARE")){
    
    
            return new Square();
        }
        return null;
    }
}

step 4

Using this factory, get an object of the entity class by passing the type information.

FactoryPatternDemo.java

/**
 * 步骤4:使用该工厂,通过传递类型信息来获取实体类的对象
 */
public class FactoryPatterDemo {
    
    

    public static void main(String[] args) {
    
    
        ShapeFactory shapeFactory = new ShapeFactory();

        // 获取 Circle 的对象,并调用它的 draw 方法
        Shape shape1 = shapeFactory.getShape("CIRCLE");
        // 调用 Circle 的 draw 方法
        shape1.draw();

        //获取 Rectangle 的对象,并调用它的 draw 方法
        Shape shape2 = shapeFactory.getShape("RECTANGLE");
        //调用 Rectangle 的 draw 方法
        shape2.draw();

        //获取 Square 的对象,并调用它的 draw 方法
        Shape shape3 = shapeFactory.getShape("SQUARE");
        //调用 Square 的 draw 方法
        shape3.draw();
    }
}

step 5

Execute the program and output the result:

Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.

screenshot analysis

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-Fj1llbE4-1668648072188)(../../images/image-20221115223614920.png)]

Guess you like

Origin blog.csdn.net/QRLYLETITBE/article/details/127897519