一、意图
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
二、适用性
当一个系统应该独立于它的产品创建、构成和表示时,要使用Prototype模式;以及
- 当要实例化的类是在运行时刻指定时,例如,通过动态装载;或者
- 为了避免创建一个类与产品类层次平行的工厂类层次时,或者
- 当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆他们可能比每次用合适的状态手工实例化该类更方便一些。
三、结构
四、代码
import java.util.ArrayList;
/**
* Created by Administrator on 2016/8/30.
*/
public class ConcretePrototype implements Cloneable {
private String name ;
private ArrayList<String> arrayList = new ArrayList<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList<String> getArrayList() {
return arrayList;
}
public void setArrayList(ArrayList<String> arrayList) {
this.arrayList = arrayList;
}
@Override
protected ConcretePrototype clone() throws CloneNotSupportedException {
ConcretePrototype clone = (ConcretePrototype)super.clone();
// arrayList 需要深拷贝
clone.arrayList = (ArrayList<String>) arrayList.clone();
return clone;
}
}
public class Client {
public static void main(String[] args) {
ConcretePrototype prototype = new ConcretePrototype();
prototype.setName("prototype");
ArrayList arrayList = new ArrayList();
arrayList.add("hello");
prototype.setArrayList(new ArrayList<>());
try {
ConcretePrototype clone = prototype.clone();
System.out.println("clone.name= " + clone.getName());
System.out.println("prototype.arrayList== clone.arrayList : " + (prototype.getArrayList() ==
clone.getArrayList()));
System.out.println("prototype.arrayList.equal(clone.arrayList): "+(
prototype.getArrayList().equals(clone.getArrayList())
));
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
结果:
clone.name= prototype
prototype.arrayList== clone.arrayList : false
prototype.arrayList.equal(clone.arrayList): true