Let's talk about the factory model

Classification of design patterns:

Design patterns are generally divided into three categories:

Creative pattern: factory method pattern, abstract factory pattern, singleton pattern, builder pattern, prototype pattern.

Structural mode: adapter mode, decorator mode, agent mode, appearance mode, bridge mode, combination mode and sharing mode.

Behavioral mode: strategy mode, template method mode, observer mode, iteration sub mode, responsibility chain mode, command mode, memo mode, state mode, visitor mode, mediation mode and interpreter mode.

Factory mode:

Factory mode belongs to creation mode. As the name suggests, it is the place where parts are assembled into products, that is, the factory where objects are created.

Typically, a class that is a factory has an object and multiple methods associated with it. After the caller calls this method with some parameters, the factory creates objects of the required type based on the parameters and returns them to the caller.

This design pattern can be used when we explicitly plan to create different instances under different conditions

What advantages does it have? The biggest one is loose coupling, that is, the creation of objects can be independent of the implementation of classes. Users do not need to know the class of creating objects, but they can still use it to create objects. It only needs to know the interfaces, methods and parameters to be passed to create objects of the required type,

Factory mode is divided into simple factory mode, factory method mode and abstract factory mode. Let's take a concrete look at their differences

1. Simple factory mode

Concept: the interface is allowed to create objects, but the object creation logic will not be exposed. It is similar to the factory method pattern, so I won't repeat it here

A problem with simple factories is that the creation of objects depends on factory classes. Therefore, if you want to extend the program, you must modify the factory class, which violates the opening and closing principle (the opening and closing principle is to open to expansion and close to modification). Therefore, from the perspective of design, how to solve this problem? We can define an abstract method for creating objects and create multiple different factory classes to implement the abstract method. In this way, once we need to add new functions, we can directly add new factory classes without modifying the previous code. This method is the factory method mode we will talk about next.

2. Factory method mode

Concept: defines an abstract method to create an object. The subclass determines the class to be instantiated. The factory method pattern pushes the instantiation of the object to the subclass.
1. Create an interface

	public interface Shape {
  	 void draw();
	}

2. Create the implementation class of 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.");
   		}
	}

3. Create a factory to generate entity class objects based on the given information

public class ShapeFactory {
    
   //Use the getShape method to get an object of shape type
   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;
   }
}

4. Use the factory to obtain entity class objects by passing parameter information

public class FactoryPatternDemo {
 
   public static void main(String[] args) {
      ShapeFactory shapeFactory = new ShapeFactory();
 
      //Get the object of Circle and call its draw method
      Shape shape1 = shapeFactory.getShape("CIRCLE");
 
      //Call Circle's draw method
      shape1.draw();
 
      //Get the object of Rectangle and call its draw method
      Shape shape2 = shapeFactory.getShape("RECTANGLE");
 
      //Call the draw method of Rectangle
      shape2.draw();
 
      //Get the object of Square and call its draw method
      Shape shape3 = shapeFactory.getShape("SQUARE");
 
      //Call Square's draw method
      shape3.draw();
   }
}
//The output result is
Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.

The advantage of this mode is that if you want to add a function now, you only need to make an implementation class, and there is no need to change the ready-made code. In this way, the expansibility is better! However, each time a product is added, a specific class and object implementation factory need to be added, which makes the number of classes in the system multiply, 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.

3. Abstract factory mode

The main purpose of abstract factory pattern is to provide an interface to create a series of related objects without specifying specific classes. The factory method delegates the task of creating instances to subclasses, while the goal of the abstract factory method is to create a series of related objects.







Keywords: Java Design Pattern Back-end

Added by colesw on Thu, 27 Jan 2022 13:49:09 +0200