什么是 Prototype 模式?
Prototype(原型)模式是一种创建型设计模式,通过复制现有对象来创建新对象,而不是通过实例化类来创建对象。这种模式在需要生成大量相似对象时非常有用。
模式结构
Prototype 模式的核心角色包括:
- Prototype(原型接口):声明一个
clone()
方法,用于复制对象。 - ConcretePrototype(具体原型):实现
clone()
方法,完成自身的复制。 - Client(客户端):通过调用原型对象的
clone()
方法创建新对象。
以下是 Prototype 模式的 UML 类图:
代码示例
以下是一个 Java 示例,展示 Prototype 模式的基本用法:
// 原型接口
interface Prototype extends Cloneable {
Prototype clone();
}
// 具体原型
class ConcretePrototype implements Prototype {
private String name;
public ConcretePrototype(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public Prototype clone() {
try {
return (Prototype) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}
// 客户端
public class PrototypePatternDemo {
public static void main(String[] args) {
ConcretePrototype prototype = new ConcretePrototype("Prototype 1");
ConcretePrototype clone = (ConcretePrototype) prototype.clone();
System.out.println("原型对象: " + prototype.getName());
System.out.println("克隆对象: " + clone.getName());
}
}
动作流程
以下是 Prototype 模式的动作流程图:
深拷贝与浅拷贝
- 浅拷贝:复制对象时,只复制对象本身及其基本数据类型的字段,而引用类型字段仍然指向原始对象的内存地址。
- 深拷贝:复制对象时,不仅复制对象本身,还递归复制引用类型字段,生成独立的对象。
以下是浅拷贝和深拷贝的示例:
// 深拷贝示例
class DeepPrototype implements Cloneable {
private String name;
private List<String> list;
public DeepPrototype(String name, List<String> list) {
this.name = name;
this.list = new ArrayList<>(list);
}
@Override
public DeepPrototype clone() {
return new DeepPrototype(this.name, new ArrayList<>(this.list));
}
}
优点
- 提高性能:通过克隆而不是实例化类,可以显著减少对象的创建成本。
- 简化对象创建:隐藏了创建对象的复杂过程,客户端无需关心具体实现。
- 动态扩展对象:可以在运行时动态创建对象。
缺点
- 复杂的深拷贝实现:如果对象包含嵌套的复杂结构,实现深拷贝会增加代码复杂性。
- 对类支持的要求:需要类实现
Cloneable
接口,并处理可能的克隆异常。
Android 中的 Prototype 模式应用
在 Android 开发中,Prototype 模式被广泛应用于对象的复用和状态复制,以下是几个典型的例子:
-
Intent
的复制:Intent
类支持复制操作,允许开发者快速创建相似的 Intent 实例。- 示例:
Intent originalIntent = new Intent(context, TargetActivity.class); originalIntent.putExtra("key", "value"); Intent clonedIntent = new Intent(originalIntent);
-
Bitmap
的复制:- 通过
Bitmap.createBitmap()
方法,可以基于现有的Bitmap
创建一个新的实例。 - 示例:
Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image); Bitmap clonedBitmap = originalBitmap.copy(originalBitmap.getConfig(), true);
- 通过
-
Bundle
的深拷贝:Bundle
提供了方法来复制其内容,用于传递数据。- 示例:
Bundle originalBundle = new Bundle(); originalBundle.putString("key", "value"); Bundle clonedBundle = new Bundle(originalBundle);
总结
Prototype 模式通过克隆现有对象来创建新对象,有助于提高对象创建的性能和灵活性。在 Android 开发中,Prototype 模式被广泛应用于对象的复制与复用,是设计高效代码的重要工具之一。