Cloneable interface and clone() method of Prototype pattern in Java SDK

Prototype pattern is a kind of creative design pattern, which uses prototype objects to create new objects without coupling with the classes of specific objects. In the Java SDK, the implementation of the Prototype pattern mainly depends on the Cloneable interface and the clone() method. 1. Cloneable interface: The Cloneable interface is an empty interface that simply identifies a class that can be replicated. Classes that implement the Cloneable interface can use the clone() method to create copies of objects. 2. Clone () method: The clone () method is a protected method in the Object class that is used to create and return a copy of the object that called it. To use the clone () method, you need to override it in a custom class and call super. clone () in the method. The following is a complete source code example of the framework code using the Prototype pattern: class Prototype implements Cloneable { private String name; public Prototype(String name) { this.name = name; } public String getName() { return name; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } } public class Main { public static void main(String[] args) throws CloneNotSupportedException { Prototype prototype = new Prototype("Prototype"); Prototype clone = (Prototype) prototype.clone(); System.out.println("Original: " + prototype.getName()); System.out.println("Clone: " + clone.getName()); } } In the above example, a prototype class Prototype was created and the Cloneable interface was implemented. In the main method of the Main class, a prototype object prototype is first created, and then a clone object clone is created by calling the clone () method. Finally, print the names of the prototype object and the cloned object separately. Summary: Prototype pattern creates new objects by copying existing objects to avoid coupling with specific object classes. In Java, the implementation of the Prototype pattern depends on the Cloneable interface and the clone() method. It should be noted that when creating an object using the Prototype pattern, the constructor of the prototype object will not be executed, and the object copy is achieved by calling the clone () method.