定义:
用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。
类图:
原型模式浅拷贝:
public class Prototype implements Cloneable {
public Prototype clone() {
Prototype prototype = null;
try {
prototype = (Prototype) super.clone();
} catch (CloneNotSupportedException e) {
// TODO: handle exception
e.printStackTrace();
}
return prototype;
}
}
public class ConcretePrototype extends Prototype {
public void show() {
System.out.println("原型模式实现类");
}
}
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
ConcretePrototype cp = new ConcretePrototype();
for (int i = 0; i < 10; i++) {
ConcretePrototype clonecp = (ConcretePrototype)cp.clone();
clonecp.show();
}
}
}
原型模式深拷贝:
public class Person implements Cloneable{
public String _mname;
public Person() {
_mname = "Nick";
}
public Person clone() {
Person _mPerson = null;
try {
_mPerson = (Person) super.clone();
// prototype._mList = this._mList;
} catch (CloneNotSupportedException e) {
// TODO: handle exception
e.printStackTrace();
}
return _mPerson;
}
}
public class Prototype implements Cloneable {
Person _mPerson = new Person();
public Prototype clone() {
Prototype prototype = null;
try {
prototype = (Prototype) super.clone();
prototype._mPerson = (Person)this._mPerson.clone();
} catch (CloneNotSupportedException e) {
// TODO: handle exception
e.printStackTrace();
}
return prototype;
}
}
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
ConcretePrototype cp = new ConcretePrototype();
for (int i = 0; i < 10; i++) {
ConcretePrototype clonecp = (ConcretePrototype)cp.clone();
clonecp.show();
System.out.println(clonecp._mPerson._mname);
}
}
}
注意:
使用原型模式复制对象不会调用类的构造方法。因为对象的复制是通过调用Object类的clone方法来完成的,它直接在内存中复制数据,因此不会调用到类的构造方法,和所有的方法,只clone基本数据类型。