Prototype mode is also a created design pattern, creating new objects by copying prototypes, understanding that prototype patterns must understand shallow and deep replication in Java. Replication is also known as cloning. deep copies will occur with 8 of the basic types in Java and their package types, plus the string type. The rest are shallow copies.
Shallow clone: A shallow clone simply clones the object being considered, not the object it refers to.
Deep cloning: A deep clone not only clones the object being considered, but also clones the object it refers to.
Its core is the prototype class prototype. The prototype class needs to have the following two conditions:
- Implements the Cloneable interface. In the Java language, there is a cloneable interface, which only works by notifying the virtual machine at runtime that it can safely use the Clone method on classes that implement this interface. In a Java virtual machine, only classes that implement this interface can be copied, or clonenotsupportedexception exceptions will be thrown at run time.
- Override the Clone method in the object class. In Java, the parent class of all classes is the object class, and the object class has a Clone method that returns a copy of the object, but its scope is protected type, and the generic class cannot be called, so The prototype class needs to modify the scope of the Clone method to the public type. Implement an interface, overriding a method that completes the prototype pattern.
Implementation class
Class Prototype implements cloneable {public Prototype clone () {Prototype Prototype = Null;try{prototype = (Prototype) supe R.clone ();} catch (Clonenotsupportedexception e) {e.printstacktrace ();} return prototype; }}
Concrete Implementation Class
Class Concreteprototype extends Prototype{public void Show () {SYSTEM.OUT.PRINTLN ("prototype Pattern implementation class");}}
Client class
public class Client {public static void main (string[] args) {concreteprototype CP = new Concreteprototype (); for (int i=0; i& Lt 10; i++) {Concreteprototype CLONECP = (concreteprototype) cp.clone (); Clonecp.show ();}}}
Java Design Pattern---prototype mode