原型模式
**当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。
**
原型模式主要就是通过clone方式来创建对象,不需要每次new,这样会多次调用构造方法,次数多了之后影响效率。
原型模式比较简单,就不写具体demo代码了,主要的就是涉及到浅复制和深复制的问题。
浅复制:具体来说就是只是复制引用,直接用clone就是浅复制。
深复制如下:
test demo类:
public class Test implements Cloneable{
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Resume implements Cloneable {
private String name;
private String sex;
private Test test = new Test();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Test getTest() {
return test;
}
public void setTest(Test test) {
this.test = test;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Resume resume = (Resume)super.clone();
return resume;
}
}
main测试代码如下:
public class Main {
/**
* @param args
* @throws CloneNotSupportedException
*/
public static void main(String[] args) throws CloneNotSupportedException {
Resume resume1 = new Resume();
Resume resume2 = (Resume)resume1.clone();
System.out.println(resume1.hashCode() + " " + resume2.hashCode());
System.out.println(resume1.getTest().hashCode() + " " + resume2.getTest().hashCode());
}
}
因为里面存在了除了基本类型String还存在了test,且test实现了Cloneable接口,实现clone方法,这个就是深复制。
如果要把上面的代码改成浅复制,只需要把test类改成一个空的类就是浅复制。
原型模式比较简单,在此不多做详细介绍。