原型模式是一种创建型设计模式,它允许一个对象通过复制自身来创建新的对象,而不是通过实例化类来创建对象。原型模式主要用于创建复杂对象的副本,避免了重复的初始化过程。
定义原型接口
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);
}
}