prototype mode

introduce

  • Intent: Use prototype instances to specify the kind of objects to create, and create new objects by copying these prototypes.
  • Key code: 1. To implement clone operation, inherit Cloneable in JAVA, rewrite clone(), in .NET, you can use MemberwiseClone() method of Object class to realize shallow copy of object or realize deep copy through serialization. 2. The prototype pattern is also used to isolate the coupling relationship between the user of the class object and the specific type (volatile class). It also requires these "volatile classes" to have stable interfaces.
  • Advantages: 1. Improved performance. 2. Escape the constraints of the constructor.
  • Disadvantages: 1. Equipping the clone method requires comprehensive consideration of the functions of the class, which is not difficult for a brand-new class, but not necessarily easy for an existing class, especially when a class refers to an indirect object that does not support serialization, Or when the reference contains a cyclic structure. 2. The Cloneable interface must be implemented.
  • Usage scenarios: 1. Resource optimization scenarios. 2. Class initialization needs to digest a lot of resources, including data and hardware resources. 3. Scenarios with performance and security requirements. 4. To generate an object through new requires very tedious data preparation or access rights, you can use the prototype mode. 5. A scene with multiple modifiers for one object. 6. When an object needs to be provided to other objects for access, and each caller may need to modify its value, you can consider using the prototype mode to copy multiple objects for the caller to use. 7. In actual projects, the prototype pattern rarely appears alone, but generally appears together with the factory method pattern. An object is created by the clone method, and then provided to the caller by the factory method. The prototype pattern has been integrated into Java, and you can use it wherever you go.
  • Note: Instead of constructing a new object by instantiating a class, the prototype pattern creates a new object by copying an existing object. Shallow copy implements Cloneable, rewrite, deep copy is to read binary stream by implementing Serializable.

accomplish

Enter image description

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 abstract class above.

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 entity classes from the database, and store them 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

Guess you like

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