The prototype pattern Prototype Pattern
uses a prototype instance to point to the class that creates objects, and is used to share prototype properties and methods of classes that create new objects.
In JavaScript
, its unique prototype inheritance feature can be used to create objects, that is, creating an object as the value of the prototype
property of another object. The prototype object effectively utilizes the objects created by each constructor, extracting common properties and methods between instances into shared properties and methods, which can be shared by instances.
In Java
, it is usually used to specify the type of object to be created by the prototype instance, and new objects are created by copying these prototypes. Specifically, it involves implementing the Cloneable
interface in an abstract class and overriding the clone
method in the Object
class. Then, subclasses can inherit this abstract class and use a collection class such as HashTable
to store in a cache class. When a class is needed, it can be found in the HashTable
and a new subclass can be obtained through clone
using the prototype pattern to create objects is much more efficient than directly using the new
keyword, because the clone
method of the Object
class is a native method that directly operates on the binary stream in memory. The performance difference is particularly noticeable when copying large objects. Another benefit of using the prototype pattern is to simplify the creation of objects, making it as simple as copying and pasting when editing a document. Therefore, when there is a need to repeatedly create similar objects, the prototype pattern can be considered. In addition, in the context of deep copy and shallow copy issues, deep copy occurs with 8
basic types in Java
and their wrapper types as well as the String
type, while everything else is shallow copy.