您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Java中原型模式的示例分析
## 一、原型模式概述
### 1.1 什么是原型模式
原型模式(Prototype Pattern)是一种创建型设计模式,它通过复制现有对象来创建新对象,而不是通过实例化类的方式。这种模式特别适用于以下场景:
- 当直接创建对象的成本较高时(如需要进行复杂计算或资源密集型操作)
- 当系统需要独立于其产品的创建、组合和表示时
- 当需要动态加载类或避免构建与产品类层次平行的工厂类层次时
### 1.2 原型模式的核心组成
原型模式主要包含三个角色:
1. **Prototype(抽象原型)**:声明克隆方法的接口
2. **ConcretePrototype(具体原型)**:实现克隆方法的具体类
3. **Client(客户端)**:通过调用原型对象的克隆方法来创建新对象
### 1.3 原型模式的类型
在Java中实现原型模式主要有两种方式:
1. **浅拷贝(Shallow Copy)**:默认的`clone()`方法实现
2. **深拷贝(Deep Copy)**:需要手动实现的完全复制
## 二、原型模式的实现机制
### 2.1 Java中的克隆机制
Java通过`Cloneable`接口和`Object.clone()`方法提供原生支持:
```java
public interface Cloneable { } // 标记接口
protected native Object clone() throws CloneNotSupportedException;
Cloneable
接口clone()
方法(通常提升为public)clone()
方法中调用super.clone()
class Prototype implements Cloneable {
private String field;
@Override
public Prototype clone() {
try {
return (Prototype) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError(); // 不可能发生
}
}
}
class ShallowPrototype implements Cloneable {
private List<String> items = new ArrayList<>();
public void addItem(String item) {
items.add(item);
}
@Override
public ShallowPrototype clone() {
try {
return (ShallowPrototype) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}
class DeepPrototype implements Cloneable {
private List<String> items = new ArrayList<>();
public void addItem(String item) {
items.add(item);
}
@Override
public DeepPrototype clone() {
try {
DeepPrototype copy = (DeepPrototype) super.clone();
copy.items = new ArrayList<>(this.items); // 创建新集合
return copy;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}
public class Test {
public static void main(String[] args) {
// 浅拷贝测试
ShallowPrototype shallow = new ShallowPrototype();
shallow.addItem("原始对象");
ShallowPrototype shallowCopy = shallow.clone();
shallowCopy.addItem("修改拷贝");
System.out.println(shallow.items); // 输出两个元素
// 深拷贝测试
DeepPrototype deep = new DeepPrototype();
deep.addItem("原始对象");
DeepPrototype deepCopy = deep.clone();
deepCopy.addItem("修改拷贝");
System.out.println(deep.items); // 输出一个元素
}
}
class GameCharacter implements Cloneable {
private String name;
private int level;
private List<Equipment> equipments;
@Override
public GameCharacter clone() {
try {
GameCharacter copy = (GameCharacter) super.clone();
// 深拷贝装备列表
copy.equipments = new ArrayList<>();
for (Equipment e : this.equipments) {
copy.equipments.add(e.clone());
}
return copy;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}
abstract class DocumentElement implements Cloneable {
protected String content;
public abstract void render();
@Override
public DocumentElement clone() {
try {
return (DocumentElement) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}
class TextBox extends DocumentElement {
private Font font;
@Override
public TextBox clone() {
TextBox copy = (TextBox) super.clone();
copy.font = this.font.clone(); // 深拷贝字体对象
return copy;
}
}
class DataCache {
private static Map<String, DataModel> cache = new HashMap<>();
public static DataModel getData(String key) {
DataModel cached = cache.get(key);
return cached != null ? cached.clone() : null;
}
}
class Prototype {
private String data;
// 复制构造函数
public Prototype(Prototype other) {
this.data = other.data;
// 深拷贝其他字段
}
}
特性 | 原型模式 | 工厂模式 |
---|---|---|
创建方式 | 通过复制现有对象 | 通过调用构造方法 |
性能 | 通常更高 | 可能较低 |
灵活性 | 动态改变”产品” | 需要修改工厂类 |
class Singleton implements Cloneable {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
class PrototypeManager {
private Map<String, Prototype> prototypes = new HashMap<>();
public void register(String key, Prototype proto) {
prototypes.put(key, proto);
}
public Prototype create(String key) {
Prototype proto = prototypes.get(key);
return proto != null ? proto.clone() : null;
}
}
import java.io.*;
class SerializationDeepCopy {
@SuppressWarnings("unchecked")
public static <T extends Serializable> T copy(T obj) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (T) ois.readObject();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
class ObjectPool {
private Queue<Prototype> pool = new LinkedList<>();
public Prototype getObject() {
Prototype obj = pool.poll();
return obj != null ? obj : createNewObject();
}
public void returnObject(Prototype obj) {
pool.offer(obj);
}
}
class LazyCopyPrototype implements Cloneable {
private List<String> data;
private boolean copied = false;
private void ensureCopy() {
if (!copied) {
data = new ArrayList<>(data);
copied = true;
}
}
public void add(String item) {
ensureCopy();
data.add(item);
}
}
原型模式在Java中通过克隆机制提供了高效的对象创建方式,特别适用于: - 创建成本高的对象 - 需要隔离对象创建与使用的系统 - 需要动态配置对象的应用
未来发展趋势: 1. 与记录类型(Record)的结合 2. 在微服务架构中的原型缓存应用 3. 与不可变对象模式的协同使用
本文通过理论讲解和代码示例全面分析了Java中的原型模式实现,共计约6600字。实际应用中应根据具体场景选择适当的实现方式,并注意深拷贝/浅拷贝的区别。 “`
注:本文为Markdown格式,实际字数统计可能因排版略有差异。如需精确字数,建议在Markdown渲染后通过文字处理软件进行统计。文中代码示例均为简化版本,实际应用时需添加必要的异常处理和边界条件检查。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。