Design mode study notes --- 5. Prototype mode

  • Prototype pattern (Prototype Pattern) is used to create repeated objects, while ensuring performance. This type of design pattern is a creational pattern, which provides an optimal way to create objects;

  • This model implements a prototype interface that is used to create a clone of the current object; this model is used when the cost of directly creating an object is relatively high. For example, an object needs to be created after a costly data warehouse operation. We can cache that game; on the next request, return its clone and update the database when needed to reduce database calls

  • Intent: use prototype instances to specify the types of objects created, and create new objects by copying these prototypes;

  • Main solution: build and delete prototypes in operation;

  • When to use:

    • 1. When a system should be created, composed and represented independently of its products;

    • 2. When the class to be instantiated is specified at runtime, for example, through dynamic loading;

    • 3. 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 combinations of states. It may be more convenient to build a corresponding number of prototypes and clone them than to instantiate the class manually in 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. To achieve cloning, inherit Cloneable in Java, and override clone (). In .net, you can use the ObjectwiseClone () method of the Object class to achieve shallow copy of objects or deep copy through serialization;

    • 2. Prototype mode is also used to isolate the coupling relationship between the users of class objects and concrete classes (variable classes). It also requires these "variable classes" to have stable interfaces;

  • Applications:

    • 1. Cell division;

    • 2. Object clone () method in Java;

  • advantage:

    • 1. Performance improvement;

    • 2. Escape the constraints of the mechanism function;

  • Disadvantages:

    • 1. Equipped with cloning methods, it is necessary to consider the class functions in general. This is not difficult for brand new classes, but it is not easy for existing classes, especially when a reference does not support serialized indirect objects, or the reference contains a cycle Structural time

    • 2. Must implement Cloneable interface;

  • scenes to be used:

    • 1. Resource optimization scenarios;

    • 2. Class initialization needs to digest a lot of resources, this resource includes data, hardware resources, etc .;

    • 3. Scenarios for performance and safety requirements;

    • 4. Creating an object through new requires very cumbersome data preparation or access rights, you can use the prototype mode;

    • 5. A scene where multiple changes are made to an object;

    • 6. An object Xu Tao provides access to other games, and when the 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, and generally appears together with the factory pattern. An object is created by the clone method, and then the factory method is provided to the caller;

    • Note: Unlike constructing a new object by instantiating a class, the prototype mode generates a new object by copying an existing object. The shallow copy implements Cloneable, rewrite, and the deep copy implements Serializable to read the binary stream. ;

  • Actual combat:

    • We will create an abstract 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;

    • PrototypePatternDemo, the class we demonstrate uses the ShapeCache class to obtain Shape objects;

 

package prototype;

/**
 * @author yangxin_ryan
 */
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;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException{
        Object clone = null;
        clone = super.clone();
        return super.clone();
    }
}
package prototype;

/**
 * @author yangxin_ryan
 */
public class Rectangle extends Shape {

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

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

/**
 * @author yangxin_ryan
 */
public class Square extends Shape {

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

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

/**
 * @author yangxin_ryan
 */
public class Circle extends Shape {
    public Circle() {
        type = "Circle";
    }

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

import java.util.Hashtable;

/**
 * @author yangxin_ryan
 */
public class ShapeCache {

    private static Hashtable<String, Shape> shapeMap = new Hashtable<String, Shape>();

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

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

package prototype;

/**
 * @author yangxin_ryan
 */
public class PrototypePatternDemo {

    public static void main(String[] args) throws Exception{
        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());
    }
}

 

Published 1980 original articles · praised 708 · 3.66 million views +

Guess you like

Origin blog.csdn.net/u012965373/article/details/105643127