原型模式用于克隆复杂对象,由于new一个实例对象会消耗大部分时间,所以原型模式可以节约大量时间
1 public class Sheep implements Cloneable{
2 private String name;
3 private Date birth;
4 public Sheep(String name, Date birth) {
5 this.name = name;
6 this.birth = birth;
7 }
8 @Override
9 protected Object clone(){
10 Sheep obj = null;
11 try {
12 obj = (Sheep) super.clone();
13 //深复制
14 // obj.birth = (Date) this.birth.clone();
15 } catch (CloneNotSupportedException e) {
16 e.printStackTrace();
17 }
18 return obj;
19 }
20 public String getName() {
21 return name;
22 }
23 public void setName(String name) {
24 this.name = name;
25 }
26 public Date getBirth() {
27 return birth;
28 }
29 public void setBirth(Date birth) {
30 this.birth = birth;
31 }
32
33 }
import java.util.Date;
public class Client {
public static void main(String[] args) {
Date date = new Date(1515529952L);
Sheep s1 = new Sheep("s1",date);
Sheep s2 = (Sheep) s1.clone();
System.out.println(s1.getBirth());
System.out.println(s2.getBirth());
date.setTime(15L);//修改后
System.out.println(s1.getBirth());
System.out.println(s2.getBirth());
}
}
1 浅复制
2 Sun Jan 18 20:58:49 CST 1970
3 Sun Jan 18 20:58:49 CST 1970
4 //修改后
5 Thu Jan 01 08:00:00 CST 1970
6 Thu Jan 01 08:00:00 CST 1970
7 深复制
8 Sun Jan 18 20:58:49 CST 1970
9 Sun Jan 18 20:58:49 CST 1970
10 修改后
11 Thu Jan 01 08:00:00 CST 1970 //只对s1修改
12 Sun Jan 18 20:58:49 CST 1970