1. Definition
Use the prototype instance to specify the kind of object to create and create a new object by copying the prototypes.
2. Class Diagram
3. Code examples
1 PackageCom.zhaoyangwoo.prototype;2 3 /**4 * Created by John on 16/5/8.5 */6 Public classPrototype {7 Public Static voidMain (string[] args) {8Product p1=NewProduct ();9P1.setname ("Nihao");TenP1.setage (2); OneProduct P2 =P1.clone (); A System.out.println (P2.getname ()); - } - } the - - classProductImplementscloneable{ - String name; + - Integer age; + A PublicProduct () { atSystem.out.println ("Call constructor Method"); - } - - - PublicString GetName () { - returnname; in } - to Public voidsetName (String name) { + This. Name =name; - } the * PublicInteger getage () { $ returnAge ;Panax Notoginseng } - the Public voidsetage (Integer age) { + This. Age =Age ; A } the + @Override - PublicProduct Clone () { $ Try { $ return(Product)Super. Clone (); -}Catch(clonenotsupportedexception e) { - e.printstacktrace (); the } - return NULL;Wuyi } the}
4. Examples of application scenarios
- An object is used by multiple objects and needs to be modified
- Type requires multiple objects but the initialization of the object consumes huge
Pattern implementation in 5.JAVA source code
In the JDK source code, all the classes that implement the Cloneable interface use this pattern. For example, we often say that the Calendar class
Public Abstract class Implements cloneable, comparable<calendar>
6. Thinking
- Prototype patterns and constructors
The prototype pattern of Java has been implemented in the language. Just to implement the Cloneable interface, the interface has no implementation, just a flag. If the interface is not available but the Clone method is overridden, an exception is reported when used.
In addition, the prototype in Java is a direct binary copy, performance objective, it can be explained that the copied entity is not the execution of the constructor function.
- Deep copy and shallow copy
A copy of a binary stream is a shallow copy, of course a new backup is generated for the underlying type, but for reference types, the new and old entities correspond to the same reference address. All if the entity class has a field of reference type, then
The Clone method re-assigns a space assignment to a field of the reference type.
Design Pattern Learning-prototype mode