Prototype Pattern

Prototype mode

Prototype Pattern is used to create duplicate objects while maintaining performance. This type of design pattern is a creative model that provides the best way to create objects.

This mode implements a prototype interface that is used to create clones of the current object. This mode is used when the cost of directly creating an object is relatively large. For example, an object needs to be created after a high-cost database operation. We can cache the object, return its clone on the next request, and update the database when needed to reduce database calls.


Intent: Use the prototype instance to specify the kind of objects to be created, and create new objects by copying them.

Main solution: Create and delete prototypes at runtime.

When to use: 1. When a system should be created, represented, and represented independently of its products. 2. When the class to be instantiated is specified at runtime, for example, by dynamic loading. 3. To avoid creating a factory class hierarchy that is parallel to the product class hierarchy. 4. When an instance of a class can only have one of several different combinations of states. Creating the appropriate number of prototypes and cloning them may be more convenient than manually instantiating the class with the appropriate state each time.

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

Key Code: 1. Implement the cloning operation, inherit Cloneable in JAVA, override clone(), and use the MemberwiseClone() method of the Object class in .NET to implement a shallow copy of the object or serialize to achieve deep copy. 2, the prototype mode is also used to isolate the coupling between the user of the class object and the specific type (variable class), it also requires these "variable classes" to have a stable interface.

Application example: 1. Cell division. 2. The Object clone() method in JAVA.

Advantages: 1. Performance improvement. 2. Escape the constraints of the constructor.

Disadvantages: 1, equipped with a clone method requires a comprehensive consideration of the function of the class, which is not difficult for a new class, but not necessarily easy for existing classes, especially when a class reference does not support serialized indirect objects, or references When the loop structure is included. 2. The Cloneable interface must be implemented.

Usage scenarios: 1. Resource optimization scenarios. 2, class initialization needs to digest a lot of resources, this resource includes data, hardware resources and so on. 3. Scenarios for performance and security requirements. 4. Prototype mode can be used when generating an object via new requires very tedious data preparation or access. 5. A scene of multiple modifiers of an object. 6, an object needs to be provided to other objects to 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, usually in conjunction with the factory method pattern, creating an object via the clone method, which is then provided to the caller by the factory method. The prototype mode has been integrated with Java and can be used at your fingertips.

Note: Unlike the construction of a new object by instantiating a class, the prototype pattern is to create a new object by copying an existing object. Shallow copy implementations Cloneable, rewrite, and deep copy are binary streams that are read by implementing Serializable.


We will 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 the shape objects in an Hashtable and returns their clones when requested.

PrototypePatternDemo, our demo class uses the ShapeCache class to get the Shape object prototype pattern_uml diagram

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) { = 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.

public class Rectangle extends Shape { public Rectangle(){ type = "< Span class="hl-string">Rectangle"; } @Override public void draw() { System.out< Span class="hl-code">.println("Inside Rectangle::draw() method."); } }

public class Square extends Shape { public Square(){ type = "< Span class="hl-string">Square"; } @Override public void draw() { System.out< Span class="hl-code">.println("Inside Square::draw() method."); } }

public class Circle extends Shape { public Circle(){ type = "< Span class="hl-string">Circle"; } @Override public void draw() { System.out< Span class="hl-code">.println("Inside Circle::draw() method."); } }

Step 3

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

import java .util.< Span class="hl-identifier">Hashtable; public class ShapeCache { private static Hashtable<String, Shape> shapeMap = new Hashtable< Span class="hl-code"><String, Shape>(); public static Shape getShape(String shapeId) { Shape cachedShape = shapeMap.get(shapeId)< /span>; return (Shape) cachedShape.clone(); } // Run a database query for each shape 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< Span class="hl-brackets">("1"); shapeMap.put< Span class="hl-brackets">(circle.getId(), circle);

Step 4

PrototypePatternDemo Use the ShapeCache class to get a clone of the shape stored in Hashtable.

public class PrototypePatternDemo { public static void main(String[] args) { ShapeCache.loadCache< Span class="hl-brackets">(); Shape clonedShape = (Shape) ShapeCache.getShape("1"); System.out< Span class="hl-code">.println("Shape : " + clonedShape.getType ()); Shape clonedShape2 = (Shape) ShapeCache.getShape("2"); System.out< Span class="hl-code">.println("Shape : " + clonedShape2.getType ()); Shape clonedShape3 = (Shape) ShapeCache.getShape("3"); System.out< Span class="hl-code">.println("Shape : " + clonedShape3.getType ());

Executing the program, outputting results:

Shape : Circle
Shape : Square
Shape : Rectangle

javacodegeeks is optimized for learning.© javacodegeeks .
All Right Reserved and you agree to have read and accepted our term and condition