应用场景
享元模式,英文名Flyweight Pattern
该模式通过对象复用,来避免大量创建复杂对象
主要用于线程池,连接池等场景,实现上比较简单
代码实现
public class Product {
}
//每种类型的产品,共享一个对象
public class ProductFactory {
//对象复用池
private static final Map pool = new HashMap();
//对象使用状态
private static final Map usage = new HashMap();
synchronized public static Product obtain(String type) {
//对象不存在,创建新对象
if (!pool.containsKey(type)) {
Product product = new Product();
pool.put(type, product);
usage.put(type, true);
return product;
}
//对象正在使用
if (usage.get(type))
throw new RuntimeException("object is in usage");
//复用旧对象
usage.put(type, true);
return pool.get(type);
}
//释放对象
synchronized public static void release(Product product) {
for (String type : pool.keySet())
if (pool.get(type) == product)
usage.put(type, false);
}
}