Prototype mode (PROTOTYPE)
Prototype mode is a model that is created. As you can see from the name, the idea of this pattern is to use an object as a prototype, copy it, clone it, and produce a new object similar to the original object. In. In Java, replication objects are implemented through clone ().
Realize:
A prototype class, only need to implement the Cloneable interface, overwrite the Clone method, where the Clone method can be changed to any name, because the Cloneable interface is an empty interface, you can arbitrarily define the method name of the implementation class, such as Clonea or Cloneb, The point is super.clone () this sentence.
Keywords:
Shallow copy: After copying an object, the variables of the base data type are recreated, and the reference type, pointing to the original object.
/ * Shallow copy * /
Public Object Clone () throws clonenotsupportedexception {
Prototype proto = (Prototype) Super . Clone ();
return Proto;
}
Deep copy: After copying an object, both the base data type and the reference type are recreated. In short, deep replication is completely replicated, and shallow copying is not exhaustive.
/* Deep copy */
public object deepclone () throws ioexception, classnotfoundexception {
/* Writes the binary stream of the current object */
Bytearrayoutputstream BOS = New Bytearrayoutputstream ();
< Span style= "line-height:21px" >OBJECTOUTPUTSTREAM&NBSP;OOS&NBSP;=&NBSP; new objectoutputstream ( BOS);
oos.writeobject ( This );
/ * read out the new object generated by the binary stream */ &NBSP;
BYTEARRAYINPUTSTREAM&NBSP;BIS&NBSP;=&NBSP; new bytearrayinputstream (Bos.tobytearray ());
< Span style= "line-height:21px" >OBJECTINPUTSTREAM&NBSP;OIS&NBSP;=&NBSP; new objectinputstream ( bis);
return ois.readobject ();
}
To implement a deep copy, you need to read the binary input of the current object in the form of a stream, and then write out the object corresponding to the binary data.
Application Scenarios:
Resource optimization Scenarios
Initialization requires a lot of resources to digest, including data, hardware resources, and so on.
Scenarios for performance and security requirements
Prototype mode can be used to create an object with new data preparation and access permissions.
A scene with multiple modifiers for an object
When an object requirement is provided to other object access, and each caller may need to modify its value, consider using the prototype schema to copy multiple object callers.
In real-world projects, prototype patterns rarely appear alone, typically in conjunction with Factory mode patterns, creating an object by using clone, and then appearing together with the factory method pattern, creating an object from the Clone method and then providing it to the caller by the factory method.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Design Pattern-Prototype mode