0%

设计模式-原型模式

用原型实例指定要创建对象的种类,并且通过拷贝这些原型创建新的对象。

原型模式就是从一个对象再创建另一个可定制的对象,而不需要知道任何创建的细节。

类图

3KN3X6.md.png

实现

1
2
3
4
5
public abstract class Prototype {

public abstract Prototype 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
public class ConcretePrototype extends Prototype {

private String field;

public ConcretePrototype(String field) {
this.field = field;
}

public String getField() {
return field;
}

public void setField(String field) {
this.field = field;
}

@Override
public Prototype clone() {
return new ConcretePrototype(field);
}

@Override
public String toString() {
return "ConcretePrototype [field=" + field + "]";
}

}
1
2
3
4
5
6
7
8
9
public class Client {

public static void main(String[] args) {
Prototype prototype = new ConcretePrototype("ConcretePrototype");
ConcretePrototype clonePrototype = (ConcretePrototype) prototype.clone();
clonePrototype.setField("ClonePrototype");
}

}

也可以使用Java自带的clone方法,需要实现Cloneable接口,但这样一般实现的是浅拷贝,深拷贝可以通过对象流的读写完成,即序列化的方式。

以下是通过实现Cloneable接口来实现浅拷贝:

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
public class ConcretePrototype2 implements Cloneable {

private String field;

public ConcretePrototype2(String field) {
this.field = field;
}

public String getField() {
return field;
}

public void setField(String field) {
this.field = field;
}

@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}

@Override
public String toString() {
return "ConcretePrototype2 [field=" + field + "]";
}

}