GOF23设计模式(五)

GOF设计模式之原型模式(prototype)

具有深克隆和浅克隆两种方法,使用原型模式需要继承Cloneable,原型模式一般用在需要new对象要耗费大量资源时使用。(反序列可以实现深克隆,本文章没有实现)

浅克隆

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Sheep implements Cloneable{
private String name;
private Date birthday;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();//Object的clone方法
}
public Sheep(String name, Date birthday) {
this.name = name;
this.birthday = birthday;
}
public String getName() {
return name;
}
public Date getBirthday() {
return birthday;
}
public Sheep() {
}
public void setName(String name) {
this.name = name;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 原型模式(浅克隆)共同使用对象
*
*/
public class Client {
public static void main(String[] args) throws CloneNotSupportedException {
Date date=new Date(12345);
Sheep s1 =new Sheep("张三",date);
Sheep s2=(Sheep)s1.clone();
System.out.println(s1.getBirthday());
date.setTime(564321654);
System.out.println("修改后"+s1.getBirthday());
System.out.println(s2.getBirthday());
}
}

结果

修改时间对象会影响克隆的对象
Thu Jan 01 08:00:12 CST 1970
修改后Wed Jan 07 20:45:21 CST 1970
Wed Jan 07 20:45:21 CST 1970

深克隆

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Sheep implements Cloneable{
private String name;
private Date birthday;
@Override
protected Object clone() throws CloneNotSupportedException {
Sheep s= (Sheep)super.clone();
//深复制
s.birthday=(Date) this.birthday.clone();//把属性也克隆
return s;//返回s;
}
public Sheep(String name, Date birthday) {
this.name = name;
this.birthday = birthday;
}
public String getName() {
return name;
}
public Date getBirthday() {
return birthday;
}
public Sheep() {
}
public void setName(String name) {
this.name = name;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 原型模式(深克隆)克隆对象
*
*/
public class Client {
public static void main(String[] args) throws CloneNotSupportedException {
Date date=new Date(12345);
Sheep s1 =new Sheep("张三",date);
Sheep s2=(Sheep)s1.clone();
System.out.println(s1.getBirthday());
date.setTime(564321654);
System.out.println("修改后"+s1.getBirthday());
System.out.println(s2.getBirthday());
}
}

结果

修改时间对象不会影响克隆的对象
Thu Jan 01 08:00:12 CST 1970
修改后Wed Jan 07 20:45:21 CST 1970
Thu Jan 01 08:00:12 CST 1970

原创技术分享,您的支持将鼓励我继续创作
0%