原型模式(Prototype Pattern)是一种创建型设计模式,它允许你复制已有对象而不是每次都通过new操作符来新建。这样可以更高效地创建新对象,特别是当初始化过程复杂或者要创建的对象是不可变对象时。
在原型模式中,核心概念是一个接口或抽象类,它声明了克隆自己的方法(通常称为clone())。具体实现这个接口或继承该抽象类的类会提供一个实现克隆自身的操作。通过调用此方法,就可以快速复制出一个与原对象具有相同状态的新对象。
// 抽象原型接口
public interface Prototype<T> extends Cloneable {
T clone();
}
// 具体原型类
public class ConcretePrototype implements Prototype<ConcretePrototype> {
private String attribute;
public ConcretePrototype(String attribute) {
this.attribute = attribute;
}
// 重写clone方法以实现深度拷贝,确保原始对象和克隆对象之间的独立性
@Override
public ConcretePrototype clone() {
try {
return (ConcretePrototype) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError("Clone is not supported for " + getClass().getName(), e);
}
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
public String getAttribute() {
return attribute;
}
}
// 使用示例
public class Client {
public static void main(String[] args) {
ConcretePrototype original = new ConcretePrototype("Original Value");
// 创建一个原型的副本
ConcretePrototype clone = original.clone();
// 改变原型对象的属性
original.setAttribute("Modified Value");
// 检查克隆对象是否独立于原始对象
System.out.println("Original: " + original.getAttribute()); // 输出 Modified Value
System.out.println("Clone: " + clone.getAttribute()); // 输出 Original Value
}
}
想象一下你在制作粘土玩具,每次做新的玩具都要从一团基础的粘土开始,揉捏、塑形很费时间。原型模式就像是你可以先做好一个模型玩具,然后只需要将这个模型压成新的粘土块,就得到一个一模一样的初始形态的玩具,再稍加修改就能快速做出很多类似但不完全一样的玩具。