概述
- 定义:运用共享技术有效的支持大量细粒度的对象
- 试用场景:如果一个应用程序使用了大量的对象,而这些对象造成了很大的存储开销的时候就可以考虑使用享元模式
实现
享元模式要注意区分内部状态和外部状态
- 内部状态:不会随环境的改变而有所不同、可以共享
- 外部状态:随环境的改变而改变、不可以共享
public interface Flyweight {
void operate();
}
class ConcreteFlyweight implements Flyweight {
private String name;
public ConcreteFlyweight(String name) {
super();
this.name = name;
}
@Override
public void operate() {
System.out.println(name);
}
}
class FlyweightFactory {
private Map<String, Flyweight> flyweights = new HashMap<>();
public Flyweight getFlyweight(String name) {
Flyweight f = flyweights.get(name);
if (f == null) {
f = new ConcreteFlyweight(name);
flyweights.put(name, f);
}
return f;
}
}
// 客户端
public class Client {
public static void main(String[] args) throws Exception {
FlyweightFactory factory = new FlyweightFactory();
factory.getFlyweight("1").operate();
factory.getFlyweight("2").operate();
factory.getFlyweight("1").operate();
factory.getFlyweight("3").operate();
}
}
实际应用
java.lang.Integer
public static Integer valueOf(int i) {
// 如果缓存中存在则直接返回缓存中的对象,否则新建一个
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}