Java implements Prototype pattern
Prototype pattern is a creative design pattern, which allows to create new objects by copying (cloning) existing objects. This pattern hides the creation logic of new objects, making the code more flexible and scalable.
Applicable scenario:
1. When the process of creating objects is complex or time-consuming, you can use the Prototype pattern to copy an existing object to create a new object. This can avoid complex object initialization processes.
2. When you need to create an object similar to an existing object, you can use the Prototype pattern to copy the properties and methods of the existing object. This can reduce the repeatability of the code.
Benefits:
1. Simplify the process of creating objects and hide the creation logic. Users only need to call the clone method to create a new object without needing to know the details of the creation process.
2. Improve performance. Cloning objects avoids the overhead of creating objects by copying the properties and methods of existing objects.
3. You can dynamically add or modify the properties of the prototype to achieve personalized object creation.
The following is a complete sample code for Java:
//Define prototype interfaces
public interface Prototype {
Prototype clone()// Cloning method
}
//Specific prototype class
public class ConcretePrototype implements Prototype {
private String property;
public ConcretePrototype(String property) {
this.property = property;
}
//Implementing cloning methods
@Override
public Prototype clone() {
return new ConcretePrototype(this.property);
}
//Method for Setting and Obtaining Properties
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
}
//The client uses Prototype pattern
public class Client {
public static void main(String[] args) {
ConcretePrototype prototype = new ConcretePrototype("test");
Concrete Prototype clone=(Concrete Prototype) prototype. clone ()// Clone Objects
System. out. println (prototype. getProperty())// Output the properties of the prototype object
System. out. println (clone. getProperty())// Output properties of cloned objects
}
}
In the above code, we defined a prototype interface called 'Prototype', which includes a 'clone' method. Next, a specific prototype class' ConcretePrototype 'was defined, the prototype interface was implemented, and the' clone 'method was implemented to create new objects.
In the client, we created a prototype object 'prototype' and created a clone object 'clone' by calling the 'clone' method. Finally, the attributes of the prototype object and the cloned object were output.