Latest web development tutorials

Prototype model

Prototype model (Prototype Pattern) is used to create a duplicate object, while ensuring performance. This type of design patterns belong create schema, which provides the best way to create objects.

This model is a prototype interface, which is used to create a clone of the current object. When the direct cost of creating an object is relatively large, then using this model. For example, an object needs to be created after the database is a costly operation. We can cache the object the next time a request to return to its clone, the time needed to update the database, in order to reduce database calls.

Introduction

Intent: The prototype used to create instances of the specified object types, and create new objects by copying the prototype.

Mainly to solve: creating and deleting prototype at runtime.

When to use: 1, when a system should be independent of its product creation, composition and representation.2, when an instance of the class is to be specified at run time, for example, by dynamic loading. 3, in order to avoid creating a parallel class hierarchy and product hierarchy when factory class. 4, when an instance of a class can have a few different combinations of state in one time. Establish a corresponding number of prototypes and clone them may be more convenient than the manual each time with the appropriate state of the instance of the class.

How to solve: the use ofan existing prototype object, and quickly produce prototype object as an instance.

Key Code: 1, to achieve cloning operation, JAVA inheritance Cloneable, rewrite clone (), can be used in .NET Object class MemberwiseClone () method to achieve the object of the shallow copy or serialization way to achieve a deep copy.2, the same prototype model for coupling between the user and the specific type (variable type) isolation between the class object, it also requires that these "variable type" has a stable interface.

Application examples: 1, cell division.2, JAVA in Object clone () method.

Advantages: 1, performance is improved.2 escape constraint constructor.

Disadvantages: 1, with a cloning method requires to take into consideration the class of functions, which the new class is not difficult, but for existing classes may not be very easy, especially when a class reference does not support serialization of indirect object, or a cyclic structure containing a reference to time.2, must implement the Cloneable interface. 3, avoid constraint constructor.

Usage scenarios: 1, resource optimization scenarios.2, class initialization need to digest a lot of resources, including the resource data, hardware resources. 3, performance and safety requirements of the scene. 4, by generating a new object requires very tedious preparation or data access, you can use the prototype model. 5, a plurality of objects modified by scene. 6, an object needs to provide access to other objects, and each caller may need to modify its value, consider using a prototype model for multiple copies of objects used by the caller. 7, in the actual project, the prototype model rarely occur alone, and factory method pattern generally appear together, create an object clone method, and then provided to the caller by the factory method. And Java prototype model has been incorporated as an integral whole, it can readily be used to use.

Note: With a class by instantiating to construct the new object is different, prototype model is to generate a new object by copying an existing object.Shallow copy realize Cloneable, rewrite, a deep copy is read binary stream by implementing Serializable.

achieve

We will create an abstract classShapeand extends the entity classesShapeclass. The next step is to define the classShapeCache,the shape of such objects are stored in aHashtablein, and at the time of the request to return to their clones.

PrototypPatternDemo,our demonstration classes usingShapeCacheclass to get theShapeobject.

Prototype model UML diagram

step 1

Create an abstract class that implements the interfaceClonable.

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 entity classes above extends the 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 entity classes from the database, and stores them in aHashtablein.

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 ();
   }

   // For each shape run database queries, and create the shape // shapeMap.put (shapeKey, shape);
   // For example, we want to add three shapes 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

PrototypePatternDemouseShapeCacheclass to get the shape of the clone is stored inthe 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 output.

Shape: Circle
Shape: Square
Shape: Rectangle