Detailed explanation of prototype mode

Keywords: Design Pattern

In some systems, there is a problem of creating a large number of identical or similar objects. If you use the traditional constructor to create objects, it will be more complex, time-consuming and resource-consuming. It is very efficient to generate objects with the prototype mode, just as it is as simple as the monkey king pulling out the monkey's hair and blowing it gently to create many monkey kings.

Definition and characteristics of a prototype pattern

The definition of Prototype pattern is as follows: take an already created instance as the Prototype, and create a new object that is the same or similar to the Prototype by copying the Prototype object. Here, the Prototype instance specifies the kind of object to create. Creating objects in this way is very efficient, and you don't need to know the details of object creation at all. For example, the installation of Windows operating system is usually time-consuming, and replication is much faster. There are many examples of replication in life, which are not listed here one by one.

Advantages of prototype mode:

  • Java   The built-in prototype mode is based on the replication of memory binary stream, and its performance is better than that of directly new an object.
  • You can use deep cloning to save the state of an object, and use prototype mode to copy an object and save its state, which simplifies the process of creating an object for use when needed (for example, restoring to a certain state in History), and can assist in the implementation of undo.

Disadvantages of prototype mode:

  • You need to configure a clone method for each class
  • The clone method is located inside the class. When modifying an existing class, you need to modify the code, which violates the opening and closing principle.
  • When implementing deep cloning, you need to write more complex code, and when there are multiple nested references between objects, in order to implement deep cloning, the classes corresponding to each layer of objects must support deep cloning, which will be troublesome to implement. Therefore, deep cloning and shallow cloning need to be used properly.

2, Structure and implementation of prototype pattern

Because Java provides the clone() method of the object, it is easy to implement the prototype pattern in Java.

1. Structure of the model

The prototype pattern contains the following main roles.

  1. Abstract prototype class: Specifies the interface that the concrete prototype object must implement.
  2. Concrete prototype class: implement the clone() method of the Abstract prototype class, which is an object that can be copied.
  3. Access class: use the clone() method in the concrete prototype class to copy the new object.


Its structure is shown in Figure 1.
 


Figure 1 structure diagram of prototype mode

2. Implementation of mode

The cloning of prototype pattern can be divided into shallow cloning and deep cloning.

  • Shallow cloning: create a new object. The properties of the new object are exactly the same as the original object. For non basic type properties, it still points to the memory address of the object pointed to by the original property.
  • Deep clone: when a new object is created, other objects referenced in the attribute will also be cloned and no longer point to the original object address.


The Object class in Java provides the clone() method of shallow cloning. The specific prototype class can realize the shallow cloning of objects as long as it implements the clonable interface, which is an abstract prototype class. Its code is as follows:

//Concrete prototype class
class Realizetype implements Cloneable {
    Realizetype() {
        System.out.println("The specific prototype was created successfully!");
    }

    public Object clone() throws CloneNotSupportedException {
        System.out.println("Specific prototype copied successfully!");
        return (Realizetype) super.clone();
    }
}

//Prototype pattern test class
public class PrototypeTest {
    public static void main(String[] args) throws CloneNotSupportedException {
        Realizetype obj1 = new Realizetype();
        Realizetype obj2 = (Realizetype) obj1.clone();
        System.out.println("obj1==obj2?" + (obj1 == obj2));
    }
}

The running results of the program are as follows:

The specific prototype was created successfully!
Specific prototype copied successfully!
obj1==obj2?false

3, Application scenario of prototype pattern

The prototype pattern is generally applicable to the following scenarios.

  • Objects are the same or similar, that is, when only several individual attributes are different.
  • The cost of creating objects is large, such as long initialization time, too much CPU, or too much network resources. Resources need to be optimized.
  • Creating an object requires cumbersome data preparation or access rights, and needs to improve performance or security.
  • This kind of object is widely used in the system, and each caller needs to re assign its properties.


stay   Spring   In, prototype patterns are widely used, such as scope='prototype ', JSON.parseObject(), etc.

4, Extension of prototype pattern

The prototype pattern can be extended to the prototype pattern with prototype manager. It adds a prototype manager PrototypeManager class on the basis of the prototype pattern. This class uses HashMap to save multiple copied prototypes, and the Client class can obtain the copied prototypes through the get(String id) method of the manager. Its structure is shown in Figure 5.
 


Fig. 5 structure diagram of prototype pattern with prototype Manager


[example 3] use the prototype mode with prototype manager to generate a prototype containing figures such as "circle" and "square", and calculate its area. Analysis: in this example, because there are different graphic classes, such as "circle" and "square", their area calculation methods are different, so they need to be managed by a prototype manager. Figure 6 shows its structure diagram.
 


Figure 6 structure diagram of graphics generator
The program code is as follows:

import java.util.*;

interface Shape extends Cloneable {
    public Object clone(); //Copy

    public void countArea(); //Calculated area
}

class Circle implements Shape {
    public Object clone() {
        Circle w = null;
        try {
            w = (Circle) super.clone();
        } catch (CloneNotSupportedException e) {
            System.out.println("Copy circle failed!");
        }
    return w;
    }

    public void countArea() {
        int r = 0;
        System.out.print("This is a circle. Please enter the radius of the circle:");
        Scanner input = new Scanner(System.in);
        r = input.nextInt();
        System.out.println("Area of the circle=" + 3.1415 * r * r + "\n");
    }
}

class Square implements Shape {
    public Object clone() {
        Square b = null;
        try {
            b = (Square) super.clone();
        } catch (CloneNotSupportedException e) {
            System.out.println("Copy square failed!");
        }
        return b;
    }

    public void countArea() {
        int a = 0;
        System.out.print("This is a square. Please enter its side length:");
        Scanner input = new Scanner(System.in);
        a = input.nextInt();
        System.out.println("The area of the square=" + a * a + "\n");
    }
}

class ProtoTypeManager {
    private HashMap<String, Shape> ht = new HashMap<String, Shape>();

    public ProtoTypeManager() {
        ht.put("Circle", new Circle());
        ht.put("Square", new Square());
    }

    public void addshape(String key, Shape obj) {
    ht.put(key, obj);
    }

    public Shape getShape(String key) {
        Shape temp = ht.get(key);
        return (Shape) temp.clone();
    }
}

public class ProtoTypeShape {
    public static void main(String[] args) {
        ProtoTypeManager pm = new ProtoTypeManager();
        Shape obj1 = (Circle) pm.getShape("Circle");
        obj1.countArea();
        Shape obj2 = (Shape) pm.getShape("Square");
        obj2.countArea();
    }
}
The operation results are as follows:

This is a circle. Please enter the radius of the circle: 3
 Area of the circle = 28.2735

This is a square. Please enter its side length: 3
 Area of the square = 9

5, Advanced reading

Prototype mode is also called clone mode. If you want to know more about prototype (clone) mode, you can click to read the following article.

Posted by jfeather on Sun, 07 Nov 2021 23:18:45 -0800