Design Mode: Prototype
Definition (From Baidu encyclopedia)
Use a prototype instance to specify the type of the object to be created, and copy the prototype to create a new object.
UML class diagram:
Code:
public class Client { public static void main(String[] args) {// Director d = new Director(new ConcreteBuilder());// d.construct(); ConcretePrototype1 prototype = new ConcretePrototype1(); for (int i = 0; i < 10; i++) { ConcretePrototype1 x = (ConcretePrototype1) prototype.clone(); x.test1(); } }}public class Prototype implements Cloneable { public Prototype clone() { Prototype prototype = null; try{ prototype = (Prototype)super.clone(); }catch(CloneNotSupportedException e){ e.printStackTrace(); } return prototype; }}public class ConcretePrototype1 extends Prototype { public void test1() { System.out.println(this); System.out.println("123"); }}
Description of each part:
The Prototype class implements the Cloneable interface.
Subclass of ConcretePrototype1 Prototype
Mode description:
Copy an object instance by cloning
Copy the value of the original Instance from the cloned object
Precautions for prototype mode:
Copying objects in prototype mode does not call the class constructor. Because Object replication is completed by calling the Object class clone method, even the access permission is invalid for the prototype mode. Do you still remember the singleton mode? In Singleton mode,
As long as you set the access permission of the constructor to private, you can implement a singleton. 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.
The clone method executes a shortest copy, that is, if it is a reference type attribute, it does not copy, but only copies the reference.
Advantages and disadvantages:
Advantages:
The clone method is executed by directly copying the memory block of the VM, which is much faster than the new one.
Get the object and its status at runtime
Disadvantages:
Prototype must implement the clone method. If many reference types or even applications in objects are referenced in Prototype attributes, the clone method should be implemented recursively, which is complicated. When a reference attribute is added, will change the clone method implementation.