- Definition: Use prototype instances to specify the kind of objects to create, and create new objects by copying these prototypes;
- The core of the prototype class is how to implement the clone method:
- A Java class that can implement cloning must implement an identity interface Cloneable, indicating that this class supports being copied;
- Generic implementation method;
- Use the clone() method of the Object class;
// 1. 通用实现方法
// 通用的克隆实现方法是在具体原型类的克隆方法中实例化一个与自身类型相同的对象并将其返回,并将相关
// 参数传入新创建的对象中,保证它们的成员属性相同
class ConcretePrototype implements Prototype{
private String attr; // 成员属性
public void setAttr(String attr){
this.attr = attr;
}
public String getAttr(){
return this.attr;
}
// 克隆方法
public Prototype clone(){
Prototype prototype = new ConcretePrototype(); // 创建新对象
prototype.setAttr(this.attr);
return prototype;
}
}
// 使用: 只需要创建一个ConcretePrototype对象作为原型对象,然后调用其clone()方法即可得到对应的克隆对象
Prototype obj1 = new ConcretePrototype();
obj1.setAttr("Hello");
Prototype obj2 = obj1.clone();
// 2. 利用Object类的clone()方法
// 在派生类中覆盖基类的clone()方法,并声明为public;
// 在派生类的clone()方法中,调用super.clone();
// 派生类需实现Cloneable接口;
// Object类相当于抽象原型类,所有实现了Cloneable接口的类相当于具体原型类;
class ConcretePrototype implements Cloneable{
...
public Prototype clone(){
Object object = null;
try{
object = super.clone();
return (Prototype)object;
} catch(CloneNotSupportedException exception){
System.err.println("Not support cloneable");
return null;
}
}
...
}
References: