下面我们来学习一下原型模式。所谓的原型模式,我们可以简单的理解为是克隆模式。但是克隆也分为浅克隆和深克隆。那么为什么要使用原型模式呢?比如说我们已经创建好了一个对象。但是创建这个对象比较耗时。如果,我们再另外的创建一个对象的话,那么就会耗费更多的内存和时间。这时候,我们就可以使用原型模式。再举一个日常生活中,我们常见的例子,比如说,在考试中,A同学完成了卷子,但是完成这个卷子需要花费不少的时间。B通信看见A同学完成了卷子。于是B同学就拿A同学的卷子来进行复制,这个过程只花费了很少的时间。并且B同学在A同学的基础上进行了修改,那么A同学就可能获得比A同学更高的分数。这就是我们所谓的原型模式。在原型模式中,如果我们已经有了一个已经创建好了的对象,那么在再创建这个对象的时候,那么我们就不需要new 这个对象了。直接克隆就可以了。这是要注意的。如果是通过new 来进行创建的话,那么就只能是按部就班,一步一步来创建这个对象。但是如果是在克隆模式中,我们就可以通过将整个的对象直接复制过来。那么这样的话,就可以提高我们的效率了。
现在我们来看一个简单的例子:
import java.util.Date;
//注意这个cloneable这个接口也只是一个标志。这个和serializable接口是一样的。
public class Sheep implements Cloneable{
private String sname;
private Date birthday;
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Sheep(String sname, Date birthday) {
super();
this.sname = sname;
this.birthday = birthday;
}
public Sheep() {
super();
// TODO Auto-generated constructor stub
}
//这里是实现了浅复制或者说是浅克隆。注意这个clone方法()是Object类中的方法。
@Override
protected Object clone() throws CloneNotSupportedException{
Object obj=super.clone();
return obj;
}
}
下面我们创建一个客户端来进行调用:
import java.util.Date;
public class Client {
public static void main(String[] args){
Sheep s1=new Sheep("少丽",new Date(12334556677L));;
System.out.println(s1);
System.out.println(s1.getSname());
System.out.println(s1.getBirthday());
try {
Sheep s2=(Sheep) s1.clone();
System.out.println(s2);
System.out.println(s2.getSname());
System.out.println(s2.getBirthday());
// 当然我们也可以改变其中的属性的值。
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
最后的输出的结果为:
prototype.Sheep@2a139a55
少丽
Sun May 24 02:15:56 CST 1970
prototype.Sheep@70dea4e
少丽
Sun May 24 02:15:56 CST 1970
那么我们如何来实现深复制呢?
public class Sheep2 {
private String sname;
private Date birthday;
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Sheep2(String sname, Date birthday) {
super();
this.sname = sname;
this.birthday = birthday;
}
public Sheep2() {
super();
// TODO Auto-generated constructor stub
}
//这里要实现的是深复制,这是要注意的。
@Override
protected Object clone() throws CloneNotSupportedException {
Object obj=super.clone();
Sheep2 s=(Sheep2)obj;
s.birthday=(Date)this.birthday.clone();
return obj;
}
}
客户端的调用:
public class Client2 {
public static void main(String[] args) {
Date d=new Date(1345667889L);
Sheep2 s3=new Sheep2("少丽",d);
System.out.println(s3);
System.out.println(s3.getSname());
System.out.println(s3.getBirthday());
d.setTime(12421356654767L);
try {
Sheep2 s2 = (Sheep2) s3.clone();
System.out.println(s2);
System.out.println(s2.getSname());
System.out.println(s2.getBirthday());
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}