设计模式——原型模式

原型模式(Prototype Pattern)的简单程度仅次于单例模式和迭代器模式。其定义如下: Specify the kinds of objects to create using a prototypical instance,and create new objects by copying this prototype.(用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。)

原型模式的通用类图

原型模式的核心就是一个clone 方法,通过java 提供的Cloneable 接口来实现量产对象。

比如已经new 出来一个红色商品,现在以该商品作为原型,快速复制多个:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Prototype implements Cloneable {
private String color;

public Prototype(String color) {
this.color = color;
}

@Override
public Prototype clone() {
Prototype prototype = null;
try {
prototype = (Prototype) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return prototype;
}

public void showColor() {
System.out.println(this.color);
}
}
1
2
3
4
5
6
7
8
9
10
public class Client {
public static void main(String[] args) {
Prototype prototype = new Prototype("Red");
for (int i = 0; i <= 5; i++) {
Prototype clonePrototype = prototype.clone();
clonePrototype.showColor();
}
}
}

控制台打印:

1
2
3
4
5
6
Red
Red
Red
Red
Red
Red

原型模式的特点:

​ ● 性能优良 原型模式是在内存二进制流的拷贝,要比直接new一个对象性能好很多,特别是要在一 个循环体内产生大量的对象时,原型模式可以更好地体现其优点。

​ ● 逃避构造函数的约束 这既是它的优点也是缺点,直接在内存中拷贝,构造函数是不会执行。优点就是减少了约束,缺点也是减少了约束,需要大家在实际应用时考虑。

使用原型模式要注意以下几点:

  • 构造函数不会被执行
  • clone 方法默认是浅拷贝,要注意使用原始类型的成员变量或自行实现深拷贝
  • final 关键字与clone 方法冲突

设计模式——原型模式
https://honosv.github.io/2023/09/21/设计模式——原型模式/
作者
Nova
发布于
2023年9月21日
许可协议