This article is based on Zen of design patterns and Java and patterns.
1. specify the type of the object to be created by providing a prototype object.
Ii. Semi-support in Java
1. The ojbect class provides a clone method.
2. Java must implement cloneable to explicitly demonstrate that JavaBean supports replication.
3. If you use the cloneable interface directly, java. Lang. clonenotsupportedexception will be thrown.
4. By default, the shortest is implemented and the clone method needs to be rewritten.
Iii. Code
package com.jue.dp;public class TV implements Cloneable {private int price;private Box box;public TV(Box b, int price) {this.box = b;this.price = price;System.out.println("TV()");}public Box getBox() {return box;}public void setBox(Box box) {this.box = box;}void display() {System.out.println(box.name + " , " + price);}@Overrideprotected TV clone() throws CloneNotSupportedException {TV temp = (TV) super.clone();temp.box = box.clone();return temp;}}
package com.jue.dp;public class Box implements Cloneable {public String name = "default";@Overrideprotected Box clone() throws CloneNotSupportedException {return (Box) super.clone();}}
package com.jue.dp;public class MainClass {public static void main(String[] args) throws CloneNotSupportedException {Box b1 = new Box();TV t1 = new TV(b1, 100);t1.display();System.out.println("------------------------");TV t2 = t1.clone();t2.display();System.out.println("------------------------");b1.name = "changed";t1.display();t2.display();}}
Iv. Advantages
1. The prototype mode is to copy binary streams in the memory, which is much better than new objects.
2. Directly copy data in the memory, and the constructor will not execute it.
3. Get a value in the real-time status.
V. Disadvantages
1. the constructor will not execute.
Vi. Notes
1. If the object clone function only calls super. clone, the composite type is only a shortest copy (the array object and other composite objects in the object, but the string is a deep copy ).
2. Clone conflicts with final constants. The following is a compilation error.
package com.jue.dp;import java.util.ArrayList;public class Things implements Cloneable {private final ArrayList<String> arraylist = new ArrayList<String>();@Overrideprotected Object clone() throws CloneNotSupportedException {Things t = (Things) super.clone();t.arraylist = (ArrayList<String>) this.arraylist.clone();return super.clone();}}
VII. application scenarios
1. class initialization requires more resources.
2. The value of the object whose status needs to be recorded.
3. Using New Requires tedious preparation and restricted access permissions.