原型设计模式
原型模式: 用一个已经创建的实例作为原型,通过复制该原型对象来创建一个和原型相同或相似的新对象。
1.实现Cloneable接口
2.实现clone()方法,并调用父类clone()
一、为什么需要对象克隆呢?
以下情况需要克隆:
类图
Prototype: 抽象原型类,声明clone()方法的接口或基类,其中clone()必须由派生对象实现。简单场景中并不需要这种基类,只需要直接具体类就足够了
ConcretePrototype: 具体原型类,用于实现或扩展clone()方法的类,必须要实现clone(),因为它返回了数据的新实例。
可以在接口中声明clone()方法,因而必须在类的实现过程中实现clone(),这样会在编译阶段强制执行。多继承层次结构中,父类实现了clone(),继承它的子类将不会强制执行
二、代码示例
/**
* 原型模式
*/
class Prototype implements Cloneable {
private String label;
get....set....
protected Prototype clone() throws CloneNotSupportedException {
return (Prototype) super.clone();
}
}
class Test{
public static void main(String[] args) throws CloneNotSupportedException {
Prototype prototype = new Prototype();
prototype.setLabel("kk");
Prototype clone = prototype.clone();
String label = prototype.getLabel();
String label1 = clone.getLabel();
System.out.println(label.equals(label1)); // true
System.out.println(clone==yuanxing); //false
}
}