0%

原型模式

原型模式

克隆羊问题

现有一只羊tom,姓名为:tom,年龄为:1,颜色为:白色。请编写程序创建和tom羊属性完全相同的10只羊。

传统解决方式

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
package prototype;
public class Sheep {
private String name;
private int age;
private String color;

public Sheep(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}

public String getName() {
return name;
}

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

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package prototype;
public class Client {
public static void main(String[] args) {
Sheep sheep = new Sheep("tom",1,"白色");

Sheep sheep1 = new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());
Sheep sheep2 = new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());
Sheep sheep3 = new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());
Sheep sheep4 = new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());
Sheep sheep5 = new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());

System.out.println(sheep1); //prototype.Sheep@74a14482
System.out.println(sheep2); //prototype.Sheep@1540e19d
System.out.println(sheep3); //prototype.Sheep@677327b6
System.out.println(sheep4); //prototype.Sheep@14ae5a5
System.out.println(sheep5); //prototype.Sheep@7f31245a
}
}
  • 优点:好理解,易操作
  • 缺点:创建新的对象时,总是需要重新获取原始对象的属性,如果创建的对象比较复杂时,效率比较低
  • 总是需要重新初始化对象,不是动态获得对象运行时的状态,不够灵活

改进思路: Java 中Object类是所有类的根类,Object 类提供了一个clone0方法,该方法可以将一个Java对象复制一份, 但是需要实现clone的Java类必须要实现一个接口Cloneable,该接口表示该类能够复制且具有复制的能力=>原型模式。

原型模式类图

notes

  • Prototype:原型类,声明一-个克隆自己的接口
  • ConcretePrototype:具体的原型类,实现一一个克隆自己的操作
  • Client:让一个原型对象克隆自己,从而创建一个新的对象(属性一样)

原型模式解决克隆羊问题

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
46
47
package prototypeimprove;

public class Sheep implements Cloneable{
private String name;
private int age;
private String color;

public Sheep(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}

public String getName() {
return name;
}

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

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}

protected Sheep clone(){
Sheep sheep = null;
try{
sheep = (Sheep)super.clone();
}catch (Exception e){
System.out.println(e.getMessage());
}
return sheep;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package prototypeimprove;

public class Client {
public static void main(String[] args) {
System.out.println("原型模式完成对象的创建");
Sheep sheep = new Sheep("tom",1,"白色");

Sheep sheep1 = sheep.clone();
Sheep sheep2 = sheep.clone();
Sheep sheep3 = sheep.clone();
Sheep sheep4 = sheep.clone();
Sheep sheep5 = sheep.clone();

System.out.println(sheep1); //prototypeimprove.Sheep@74a14482
System.out.println(sheep2); //prototypeimprove.Sheep@1540e19d
System.out.println(sheep3); //prototypeimprove.Sheep@677327b6
System.out.println(sheep4); //prototypeimprove.Sheep@14ae5a5
System.out.println(sheep5); //prototypeimprove.Sheep@7f31245a
}
}

浅拷贝和深拷贝

浅拷贝

  • 对于数据类型是基本数据类型的成员变量,浅拷贝会直接进行值传递,也就是将该属性值复制一份给新的对象。
  • 对于数据类型是引用数据类型的成员变量,比如说成员变量是某个数组、某个类的对象等,那么浅拷贝会进行引用传递,也就是只是将该成员变量的引用值(内存地址)复制一份给新的对象。因为实际,上两个对象的该成员变量都指向同一个实例。在这种情况下,在一个对象中修改该成员变量会影响到另一个对象的该成员变量值。
  • 前面克隆羊是浅拷贝。
  • 浅拷贝是使用默认的Clone()方法来实现
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package prototypeimprove;

public class Sheep implements Cloneable{
private String name;
private int age;
private String color;
// private Sheep friend;私有Client不能访问
public Sheep friend;

@Override
public String toString() {
return "Sheep{" +
"name='" + name + '\'' +
", age=" + age +
", color='" + color + '\'' +
", friend=" + friend +
'}';
}

public Sheep(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}

public String getName() {
return name;
}

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

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}

protected Sheep clone(){
Sheep sheep = null;
try{
sheep = (Sheep)super.clone();
}catch (Exception e){
System.out.println(e.getMessage());
}
return sheep;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package prototypeimprove;

public class Client {
public static void main(String[] args) {
System.out.println("原型模式完成对象的创建");
Sheep sheep = new Sheep("tom",1,"白色");
sheep.friend = new Sheep("Jack",2,"黑色");

Sheep sheep1 = sheep.clone();
Sheep sheep2 = sheep.clone();
Sheep sheep3 = sheep.clone();
Sheep sheep4 = sheep.clone();
Sheep sheep5 = sheep.clone();

System.out.println("sheep1 = " + sheep1 + " sheep1.friend= " + sheep1.friend.hashCode());
System.out.println("sheep2 = " + sheep2 + " sheep2.friend= " + sheep2.friend.hashCode());
System.out.println("sheep3 = " + sheep3 + " sheep3.friend= " + sheep3.friend.hashCode());
System.out.println("sheep4 = " + sheep4 + " sheep4.friend= " + sheep4.friend.hashCode());
System.out.println("sheep5 = " + sheep5 + " sheep5.friend= " + sheep5.friend.hashCode());
}
}

运行结果:

1
2
3
4
5
sheep1 = Sheep{name='tom', age=1, color='白色', friend=Sheep{name='Jack', age=2, color='黑色', friend=null}} sheep1.friend= 1956725890
sheep2 = Sheep{name='tom', age=1, color='白色', friend=Sheep{name='Jack', age=2, color='黑色', friend=null}} sheep2.friend= 1956725890
sheep3 = Sheep{name='tom', age=1, color='白色', friend=Sheep{name='Jack', age=2, color='黑色', friend=null}} sheep3.friend= 1956725890
sheep4 = Sheep{name='tom', age=1, color='白色', friend=Sheep{name='Jack', age=2, color='黑色', friend=null}} sheep4.friend= 1956725890
sheep5 = Sheep{name='tom', age=1, color='白色', friend=Sheep{name='Jack', age=2, color='黑色', friend=null}} sheep5.friend= 1956725890

深拷贝

  • 复制对象的所有基本数据类型的成员变量值
  • 为所有引用数据类型的成员变量申请存储空间,并复制每个引用数据类型成员变 量所引用的对象,直到该对象可达的所有对象。也就是说,对象进行深拷贝要对 整个对象进行拷贝
  • 深拷贝实现方式1:重写clone方法来实现深拷贝
  • 深拷贝实现方式2:通过对象序列化实现深拷贝(推荐)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package DeepPrototype;

import java.io.Serializable;

public class DeepCloneableTarget implements Serializable, Cloneable {

private static final long serialVersionUID = 1L;

private String cloneName;
private String cloneClass;

//构造器
public DeepCloneableTarget(String cloneName, String cloneClass) {
this.cloneName = cloneName;
this.cloneClass = cloneClass;
}

//因为该类的属性,都是String,因此我们这里使用默认的clone完成即可
@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
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package DeepPrototype;

import java.io.*;

public class DeepProtoType implements Serializable,Cloneable {

public String name; //String属性
public DeepCloneableTarget deepCloneableTarget; //引用类型

public DeepProtoType(){
super();
}

//深拷贝 - 1.使用clone方法
@Override
protected Object clone() throws CloneNotSupportedException {
Object deep = null;
//这里完成对基本数据类型(属性)和String的克隆
//String也是浅拷贝,但String是个不可变类,所以呈现出深拷贝现象。
deep = super.clone();
//对引用类型的属性进行单独处理
DeepProtoType deepProtoType = (DeepProtoType)deep;
deepProtoType.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();

return deepProtoType;
}

// 深拷贝 - 2.使用序列化(推荐)
public Object deepClone() throws IOException, ClassNotFoundException {
//创建流对象
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
//序列化
try {
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(this);
//反序列化
bis = new ByteArrayInputStream(bos.toByteArray());
ois = new ObjectInputStream(bis);
DeepProtoType copyobj = (DeepProtoType)ois.readObject();
return copyobj;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} finally {
try {
bos.close();
oos.close();
bis.close();
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package DeepPrototype;

public class Client {
public static void main(String[] args) throws CloneNotSupportedException {
DeepProtoType p = new DeepProtoType();
p.name = "2333";
p.deepCloneableTarget = new DeepCloneableTarget("xxxx","yyyyy");

//方式1 完成深拷贝
DeepProtoType p1 = (DeepProtoType) p.clone();
System.out.println("p.name = " + p.name + " p.deepCloneableTarget.hashCode() = " + p.deepCloneableTarget.hashCode());
System.out.println("p1.name = " + p1.name + " p1.deepCloneableTarget.hashCode() = " + p1.deepCloneableTarget.hashCode());

//方式2 使用序列化
DeepProtoType p2 = (DeepProtoType) p.clone();
System.out.println("p.name = " + p.name + " p.deepCloneableTarget.hashCode() = " + p.deepCloneableTarget.hashCode());
System.out.println("p2.name = " + p2.name + " p2.deepCloneableTarget.hashCode() = " + p2.deepCloneableTarget.hashCode());

}
}

结果如下:

1
2
3
4
p.name = 2333 p.deepCloneableTarget.hashCode() = 1956725890
p1.name = 2333 p1.deepCloneableTarget.hashCode() = 356573597
p.name = 2333 p.deepCloneableTarget.hashCode() = 1956725890
p2.name = 2333 p2.deepCloneableTarget.hashCode() = 1735600054

原型模式的注意事项和细节

  • 创建新的对象比较复杂时,可以利用原型模式简化对象的创建过程,同时也能够提 高效率
  • 不用重新初始化对象,而是动态地获得对象运行时的状态
  • 如果原始对象发生变化(增加或者减少属性),其它克隆对象的也会发生相应的变化, 无需修改代码。
  • 在实现深克隆的时候可能需要比较复杂的代码。
  • 缺点:需要为每一个类配备一个克隆方法,这对全新的类来说不是很难,但对已有 的类进行改造时,需要修改其源代码,违背了ocp原则,这点请注意。
-------------本文结束感谢您的阅读-------------