原型设计模式
一、原型模式涉及角色
1、prototype :声明一个克隆自身的原型接口。
2、concretrPrototype:实现一个克隆自身的操作。
3、Client:让一个原型克隆自身从而创建一个对象。
二、使用场景和说明
1、当一个系统独立于它的产品的创建、构成和表示时可以使用原型模式;
2、原型模式创建对象比直接new一个对象在性能上要好很多,因为Object类的clone方法是一个本地的方法,它直接操作内存中的二进制流,特别是复制大对象时,性能差别是非常明显的。
3、使用原型模式的另一个好处就是简化对象的创建,使得创建对象就想我们在编辑文档时的复制粘贴一样简单。
1、使用克隆创建对象的时候,构造函数不会被执行,因为对象的赋值是直接调用Object类的clone方法实现的,它在内存中直接复制数据。
2、原型模式其实就是一种拷贝机制,分为深拷贝和浅拷贝执行。一些基本数据类型的拷贝 是为浅拷贝,但是对于数组、容器对象、引用对象都不会拷贝,需要自己实现深拷贝。
三、代码实例
public class Prototype implements Cloneable {
private ArrayList list = new ArrayList();
private String name;
public Prototype clone() {
Prototype prototype = null;
try {
prototype = (Prototype) super.clone();
prototype.list = (ArrayList) this.list.clone();//深拷贝
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return prototype;
}
private ArrayList list = new ArrayList();
private String name;
public Prototype clone() {
Prototype prototype = null;
try {
prototype = (Prototype) super.clone();
prototype.list = (ArrayList) this.list.clone();//深拷贝
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return prototype;
}
}
===========================================================
public class ConcretePrototype extends Prototype {
private String name;
public void show(){
System.out.println("大家好,我是 :"+name);
}
private String name;
public void show(){
System.out.println("大家好,我是 :"+name);
}
}
============================================================
public class Client {
public static void main(String[] args) {
ConcretePrototype prototype = new ConcretePrototype();
prototype.setName("原型prototype");
prototype.show();
ConcretePrototype clone001 = (ConcretePrototype) prototype.clone();
clone001.setName("clone001");
clone001.show();
ConcretePrototype clone002 = (ConcretePrototype) prototype.clone();
clone001.setName("clone002");
clone001.show();
}
}
public static void main(String[] args) {
ConcretePrototype prototype = new ConcretePrototype();
prototype.setName("原型prototype");
prototype.show();
ConcretePrototype clone001 = (ConcretePrototype) prototype.clone();
clone001.setName("clone001");
clone001.show();
ConcretePrototype clone002 = (ConcretePrototype) prototype.clone();
clone001.setName("clone002");
clone001.show();
}
}