Creation pattern--factory pattern【Factory Pattern】

factory pattern

The 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 pattern, we do not expose the creation logic to the client when creating the object, and we use a common interface to point to the newly created object.

introduce

Intent: Define an interface for creating an object, let its subclasses decide which factory class to instantiate, and the factory pattern 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 the returned product is also an abstract product.

Critical code: The creation process is performed in its subclasses.

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

Advantages: 1. If a caller wants to create an object, it 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. The specific implementation of the shielding product is shielded, and the caller only cares about the interface of the product.

Disadvantage: Every time a product is added, a specific class and object implementation factory need to be added, which doubles the number of classes in the system, increases the complexity of the system to a certain extent, and also increases the specific class of the system. rely. This is not a good thing.

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

Note: As a class creation pattern, you can use the factory method pattern anywhere you need to generate complex objects. One thing to note is that complex objects are suitable for using the factory pattern, while simple objects, especially those that can be created only 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 an entity class that implements the Shape interface. The next step is to define the factory class ShapeFactory.

FactoryPatternDemo, our demo class uses ShapeFactory to get Shape objects. It will pass information (CIRCLE/RECTANGLE/SQUARE) to ShapeFactory to get the type of object it needs.

UML diagram of factory pattern

Step 1. Create an interface Shape.java

public interface Shape {
   void draw();
}

Step 2. Create an entity class Rectangle.java that implements the interface

public class Rectangle implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
   }
}

Square.java

public class Square implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Square::draw() method.");
   }
}

Circle.java

public class Circle implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Circle::draw() method.");
   }
}

Step 3. Create a factory that generates objects of entity classes based on the given information.

ShapeFactory.java

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. Use the factory to obtain the object of the entity class by passing the type information.

FactoryPatternDemo.java

public class FactoryPatternDemo {

   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. Verify the output.

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

Reference documents:
1. https://www.w3cschool.cn/shejimoshi/factory-pattern.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325325054&siteId=291194637