整体设计思路
- 缓存机制引入:
- 可以使用
HashMap
作为简单的缓存容器,以原型对象的标识(如唯一ID)作为键,缓存的克隆对象作为值。
- 在获取原型对象的克隆实例时,先检查缓存中是否存在,如果存在则直接返回缓存对象,否则通过原型模式创建新对象并缓存。
- 与单例模式融合:
- 将缓存管理类设计为单例,确保整个项目中只有一个缓存实例,避免重复缓存造成内存浪费。
- 与工厂模式融合:
- 工厂模式负责对象的创建逻辑,结合原型模式的克隆机制,在工厂类中通过缓存机制优化对象创建过程。
关键代码片段伪代码实现
原型接口及实现类
// 原型接口
interface Prototype {
Prototype clone();
}
// 具体原型类
class ConcretePrototype implements Prototype {
private String data;
public ConcretePrototype(String data) {
this.data = data;
}
@Override
public Prototype clone() {
// 这里可根据实际情况实现深拷贝或浅拷贝
return new ConcretePrototype(data);
}
}
缓存管理单例类
class CacheManager {
private static CacheManager instance;
private Map<String, Prototype> cache;
private CacheManager() {
cache = new HashMap<>();
}
public static CacheManager getInstance() {
if (instance == null) {
synchronized (CacheManager.class) {
if (instance == null) {
instance = new CacheManager();
}
}
}
return instance;
}
public Prototype getFromCache(String key) {
return cache.get(key);
}
public void putInCache(String key, Prototype prototype) {
cache.put(key, prototype);
}
}
工厂类
class ObjectFactory {
public Prototype createObject(String key, String data) {
CacheManager cacheManager = CacheManager.getInstance();
Prototype prototype = cacheManager.getFromCache(key);
if (prototype == null) {
prototype = new ConcretePrototype(data);
cacheManager.putInCache(key, prototype.clone());
}
return prototype.clone();
}
}
使用示例
public class Main {
public static void main(String[] args) {
ObjectFactory factory = new ObjectFactory();
Prototype prototype1 = factory.createObject("1", "data1");
Prototype prototype2 = factory.createObject("1", "data1");
// prototype1 和 prototype2 可能来自缓存,提高了性能
}
}