The Prototype pattern is a creational design pattern that lets you copy existing objects without making your code dependent on their classes. This pattern is especially useful when the construction of an object is costly or complex.
定义原型接口
java
public interface Prototype extends Cloneable {
Prototype clone();
}
创建具体原型类
java
public class ConcretePrototype implements Prototype {
private String name;
public ConcretePrototype(String name) {
this.name = name;
}
@Override
public Prototype clone() {
try {
return (Prototype) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "ConcretePrototype{name='" + name + "'}";
}
}
使用原型模式
java
public class PrototypePatternDemo {
public static void main(String[] args) {
ConcretePrototype prototype1 = new ConcretePrototype("Prototype 1");
ConcretePrototype prototype2 = (ConcretePrototype) prototype1.clone();
System.out.println(prototype1);
System.out.println(prototype2);
prototype2.setName("Prototype 2");
System.out.println(prototype1);
System.out.println(prototype2);
}
}