Factory pattern of Java design pattern

Factory mode (factory pattern) is one of the most commonly used design patterns in Java. This type of design pattern belongs to the creation mode, which provides the best way to create objects. In factory mode, we do not expose the creation logic to the client when creating objects, and point to the newly created objects by using a common interface. We only focus on creating factories Object. Different subclasses are obtained by passing different parameters to the factory object.

introduce

intention

Define an interface for creating objects, and let its subclasses decide which factory class to instantiate. The factory pattern delays the creation process to the subclasses.

Main solution

It mainly solves the problem of interface selection. We choose for us through the factory. For those who do not know, as long as we pass in parameters, the factory will automatically select a class for us.

When to use

We explicitly plan to create different instances under different conditions.

How to solve

Let its subclasses implement the factory interface and return an abstract product. That is, the interface class is actually returned.

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 implementation in the car. 2. Hibernate database only needs to change dialect and driver.

advantage

1. A caller wants to create an object, just know its name. 2. High scalability. If you want to add a product, you can only extend a factory class. 3. Mask the specific implementation of the product, and the caller only cares about the product interface.

shortcoming

Each time you add a product, you need to add a specific class and object implementation factory, so that the number of classes in the system increases exponentially, which not only increases the complexity of the system to a certain extent, but also increases the dependence of the specific classes of the system. This is not a good thing.

Usage scenario

1. Log recorder: records may be recorded to local hard disk, system events, remote servers, etc. users can choose where to record logs. 2. Database access, when the user does not know what kind of database the system uses and the database may change. 3. Designing a framework for connecting to a server requires three protocols, "POP3", "IMAP" and "HTTP", which can be used as product classes to jointly implement an interface.

matters needing attention

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

realization

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 obtain shape objects. It passes information (circle / rectangle / square) to shapefactory to get the type of object it needs.

Step 1

public interface Shape {
   void draw();
}

Step 2

Create an implementation class for the interface

public class Rectangle implements Shape {
 
   @Override
   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
   }
}
public class Square implements Shape {
 
   @Override
   public void draw() {
      System.out.println("Inside Square::draw() method.");
   }
}
public class Circle implements Shape {
 
   @Override
   public void draw() {
      System.out.println("Inside Circle::draw() method.");
   }
}

Step 3

Create a factory to generate objects of entity classes based on the given information.

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, the object of the entity class is obtained by passing type information.

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

Execute the program and output the results

Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>