0%

Java原型模式深浅克隆

浅克隆

对于浅克隆,对象是克隆了,但是里面的类确实用的同一个,示例如下:

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* @author xixing
* @version 1.0
* @date 2020/6/2 19:08
*/
public class Pig implements Cloneable {


private String name;
private Date birthday;

public Pig(String name, Date birthday) {
this.name = name;
this.birthday = birthday;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Date getBirthday() {
return birthday;
}

public void setBirthday(Date birthday) {
this.birthday = birthday;
}

@Override
public String toString() {
return "Pig{" +
"name='" + name + '\'' +
", birthday=" + birthday +
'}'+super.toString();
}

@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* @author xixing
* @version 1.0
* @date 2020/6/2 19:12
*/
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
Date birthday=new Date(0);
Pig pig1=new Pig("佩奇",birthday);
Pig pig2= (Pig) pig1.clone();
System.out.println(pig1);
System.out.println(pig2);
pig1.getBirthday().setTime(4839480394034L);
System.out.println(pig1);
System.out.println(pig2);

}
}

输出

image-20200602192237120

深克隆

1
2
3
4
5
6
7
@Override
protected Object clone() throws CloneNotSupportedException {
Pig pig= (Pig) super.clone();
//深克隆
pig.birthday= (Date) pig.birthday.clone();
return pig;
}

image-20200602192654029

对克隆的反射攻击破坏单例模式

1
2
3
4
5
6
HungrySingleton hungrySingleton=HungrySingleton.getInstance();
Method method = hungrySingleton.getClass().getDeclaredMethod("clone");
method.setAccessible(true);
HungrySingleton hungrySingleton1 = (HungrySingleton) method.invoke(hungrySingleton);
System.out.println(hungrySingleton);
System.out.println(hungrySingleton1);

解决方案

1
2
3
4
@Override
protected Object clone() throws CloneNotSupportedException {
return getInstance();
}

或者不实现Cloneable