Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Prototype mode


May 27, 2021 Design mode


Table of contents


Prototype mode

Prototype Pattern is used to create duplicate objects while guaranteeing performance. This type of design pattern belongs to the creation pattern and provides the best way to create objects.

This pattern implements a prototype interface that is used to create a clone of the current object. T his pattern is used when it is more expensive to create objects directly. F or example, an object needs to be created after a costly database operation. We can cache the object, return its clone on the next request, and update the database when needed to reduce database calls.

Introduced

Intent: Specify the kind of objects that are created with prototype instances, and create new objects by copying them.

Key solution: Build and remove prototypes during the runtime.

When to use: 1, when a system should be created, formed, and represented independently of its products. 2 , when the class to be instantiated is specified at the run time, for example, through dynamic loading. 3 , in order to avoid creating a factory class level parallel to the product class level. 4 . When an instance of a class can only have one of several different state combinations. It may be easier to build a corresponding number of prototypes and clone them than to manually instantiate the class with the appropriate state each time.

How to solve it: Use an existing prototype object to quickly generate the same instance as the prototype object.

Key code: 1, enable cloning, inherit Cloneable in JAVA, override clone(), and in .NET you can use the Object class's MemberwiseClone() method to implement a shallow copy of an object or a serialized way to achieve a deep copy. 2 . Prototype mode is also used to isolate the coupling relationship between the consumer of class objects and specific types (variable classes), which also requires that these "variable classes" have stable interfaces.

Application example: 1, cell division. 2 , object clone() method in JAVA.

Pros: 1, performance improvement. 2 , to avoid the constraints of the constructor.

Cons: 1, equipped with cloning methods need to consider the function of the class, which is not very difficult for a brand new class, but for existing classes is not necessarily easy, especially when a class reference does not support serialized indirect objects, or references contain circular structure. 2 . The Cloneable interface must be implemented. 3 , to avoid the constraints of the constructor.

Use scenes: 1, resource optimization scenarios. 2 , class initialization needs to digest a very large number of resources, including data, hardware resources. 3 , performance and safety requirements of the scene. 4 , through new to produce an object needs very tedious data preparation or access, you can use prototype mode. 5 , a scene of multiple modifiers of an object. 6 . When an object needs to be accessed by other objects, and each caller may need to modify its value, consider copying multiple objects in prototype mode for the caller to use. 7 . In the actual project, the prototype pattern rarely appears alone, usually with the factory method pattern, creating an object through the clone method, which is then provided to the caller by the factory method. P rototype patterns are already integrated with Java and can be used at your go.

Note: Unlike constructing a new object by instantiation of a class, the prototype pattern is to generate a new object by copying an existing object. The shallow copy implements Cloneable, rewrites, and the deep copy reads the binary stream by implementing Serializable.

Realize

We'll create an abstract class Shape and an entity class that extends the Shape class. The next step is to define the class ShapeCache, which stores shape objects in a Hashtable and returns their clones when requested.

PrototypPatternDemo, our demo class uses the ShapeCache class to get shape objects.

Prototype mode

Step 1

Create an abstract class that implements the Clonable interface.

Shape.java

public abstract class Shape implements Cloneable {
   
   private String id;
   protected String type;
   
   abstract void draw();
   
   public String getType(){
      return type;
   }
   
   public String getId() {
      return id;
   }
   
   public void setId(String id) {
      this.id = id;
   }
   
   public Object clone() {
      Object clone = null;
      try {
         clone = super.clone();
      } catch (CloneNotSupportedException e) {
         e.printStackTrace();
      }
      return clone;
   }
}

Step 2

Create an entity class that extends the above abstract class.

Rectangle.java

public class Rectangle extends Shape {

   public Rectangle(){
     type = "Rectangle";
   }

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

Square.java

public class Square extends Shape {

   public Square(){
     type = "Square";
   }

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

Circle.java

public class Circle extends Shape {

   public Circle(){
     type = "Circle";
   }

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

Step 3

Create a class, get the entity class from the database, and store it in a Hashtable.

ShapeCache.java

import java.util.Hashtable;

public class ShapeCache {
   
   private static Hashtable<String, Shape> shapeMap 
      = new Hashtable<String, Shape>();

   public static Shape getShape(String shapeId) {
      Shape cachedShape = shapeMap.get(shapeId);
      return (Shape) cachedShape.clone();
   }

   // 对每种形状都运行数据库查询,并创建该形状
   // shapeMap.put(shapeKey, shape);
   // 例如,我们要添加三种形状
   public static void loadCache() {
      Circle circle = new Circle();
      circle.setId("1");
      shapeMap.put(circle.getId(),circle);

      Square square = new Square();
      square.setId("2");
      shapeMap.put(square.getId(),square);

      Rectangle rectangle = new Rectangle();
      rectangle.setId("3");
      shapeMap.put(rectangle.getId(),rectangle);
   }
}

Step 4

PrototypePatternDemo uses the ShapeCache class to get clones of shapes stored in Hashtable.

PrototypePatternDemo.java

public class PrototypePatternDemo {
   public static void main(String[] args) {
      ShapeCache.loadCache();

      Shape clonedShape = (Shape) ShapeCache.getShape("1");
      System.out.println("Shape : " + clonedShape.getType());       

      Shape clonedShape2 = (Shape) ShapeCache.getShape("2");
      System.out.println("Shape : " + clonedShape2.getType());        

      Shape clonedShape3 = (Shape) ShapeCache.getShape("3");
      System.out.println("Shape : " + clonedShape3.getType());        
   }
}

Step 5

Verify the output.

Shape : Circle
Shape : Square
Shape : Rectangle