Definition:
Use a prototype instance to specify the type of the object to be created, and copy the prototype to create a new object.
Class diagram:
Advantages and applicable scenarios:
Creating an Object in the prototype mode is much better than simply creating a new Object in terms of performance, because the Object-class clone method is a local method that directly operates the binary stream in the memory, especially when copying large objects, the performance difference is very obvious.
Another advantage of using the prototype mode is to simplify object creation, making object creation as simple as copying and pasting during document editing. Because of the above advantages, you can consider using the prototype mode when you need to repeatedly create similar objects. For example, you need to create an object in a circular body. If the object creation process is complex or has a large number of cycles, you can use the prototype mode to simplify the creation process and improve the overall performance of the system.
Note:
Copying objects in prototype mode does not call the class constructor. Because the Object replication is completed by calling the Object class clone method, it directly copies data in the memory, so it does not call the class constructor. Not only will the code in the constructor not be executed, but even the access permission is invalid for the prototype. Do you still remember the singleton mode? In Singleton mode, you only need to set the access permission of the constructor method to private. However, the clone method directly ignores the permissions of the constructor. Therefore, the singleton mode conflicts with the prototype mode. Pay special attention to this mode when using it.
Deep copy and shallow copy. The clone method of the Object class only copies the basic data types in the Object, and does not copy the array, container Object, and referenced Object. This is a shortest copy. To implement deep copy, you must copy arrays, container objects, and reference objects in the prototype mode separately. For example:
[Java]
Public class Prototype implements Cloneable {
// Because ArrayList is not a basic type, the member variable list will not be copied. We need to implement deep copy by ourselves.
Private ArrayList list = new ArrayList ();
Public Prototype clone (){
Prototype prototype = null;
Try {
Prototype = (Prototype) super. clone ();
Prototype. list = (ArrayList) this. list. clone ();
} Catch (CloneNotSupportedException e ){
E. printStackTrace ();
}
Return prototype;
}
}