设计模式之原型模式(java)
定义
原型模式(Prototype) 是一种创建型设计模式,原型模式允许一个对象再创建另外一个可定制的对象,根本无需知道任何如何创建的细节。
工作原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建。
实现
原型类Prototype声明一个克隆方法,由具体原型类来继承实现该方法,其中具体实现Clone()方法又可以分为深拷贝和浅拷贝,深拷贝针对类中引用类型的元素,浅拷贝针对基本类型元素,如int char等。
具体实现代码(浅拷贝)
代码:
public abstract class Prototype implements Cloneable {
public abstract Object Clone() throws CloneNotSupportedException;
}
public class ConcretePrototype1 extends Prototype {
int id;
public ConcretePrototype1(int id) {
this.id=id;
}
public int getId() {
return this.id;
}
public Object Clone() throws CloneNotSupportedException {
//创建当前对象的浅表副本,方法是创建一个新对象,然后将当前对象的非静态字段复制道该新对象,如果字段是值类型的,则对该字段执行逐位复制,如果字段是引用类型,则复制引用但不复制引用的对象,因此,原始对象及其副本引用同一对象
return super.clone();
}
}
public class ClientTest {
public static void main(String[] args) throws Exception {
ConcretePrototype1 p1=new ConcretePrototype1(11);
ConcretePrototype1 p2=(ConcretePrototype1) p1.Clone();
System.out.println(p2==p1);
System.out.println(p2.getId());
}
}
具体实现代码(深拷贝)
public abstract class Prototype implements Cloneable {
public abstract Object Clone() throws CloneNotSupportedException;
}
public class ConcretePrototype1 extends Prototype {
int id;
Person p;
public ConcretePrototype1(int id,Person p) {
this.p=p;
this.id=id;
}
public int getId() {
return this.id;
}
public Object Clone() throws CloneNotSupportedException {
//创建当前对象的浅表副本,方法是创建一个新对象,然后将当前对象的非静态字段复制道该新对象,如果字段是值类型的,则对该字段执行逐位复制,如果字段是引用类型,则复制引用但不复制引用的对象,因此,原始对象及其副本引用同一对象
ConcretePrototype1 p1=(ConcretePrototype1) super.clone();
p1.p=(Person) p.Clone();
return p1;
}
}
class Person implements Cloneable{
String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public Object Clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class ClientTest {
public static void main(String[] args) throws Exception {
Person p=new Person();
p.setStr("zw");
ConcretePrototype1 p1=new ConcretePrototype1(11,p);
ConcretePrototype1 p2=(ConcretePrototype1) p1.Clone();
System.out.println(p1.p.getStr());
p2.p.setStr("zzz");
System.out.println(p1.p.getStr());
}
}