享元模式
享元(Flyweight)模式的定义:运用共享技术来有效地支持大量细粒度对象的复用。它通过共享已经存在的对象来大幅度减少需要创建的对象数量、避免大量相似类的开销,从而提高系统资源的利用率。
享元模式的本质是缓存共享对象,降低内存消耗。
享元模式的主要优点是:相同对象只要保存一份,这降低了系统中对象的数量,从而降低了系统中细粒度对象给内存带来的压力。
其主要缺点是:
- 为了使对象可以共享,需要将一些不能共享的状态外部化,这将增加程序的复杂性。
- 读取享元模式的外部状态会使得运行时间稍微变长。
public class FlyWeightTest {
public static void main(String[] args) {
FlyWeightFactory flyWeightFactory = new FlyWeightFactory();
FlyWeight a1 = flyWeightFactory.getFlyWeight("a");
FlyWeight a2 = flyWeightFactory.getFlyWeight("a");
FlyWeight a3 = flyWeightFactory.getFlyWeight("a");
FlyWeight b1 = flyWeightFactory.getFlyWeight("b");
FlyWeight b2 = flyWeightFactory.getFlyWeight("b");
a1.operate(new UnFlyWeight("第1次调用a。"));
a2.operate(new UnFlyWeight("第2次调用a。"));
a3.operate(new UnFlyWeight("第3次调用a。"));
b1.operate(new UnFlyWeight("第1次调用b。"));
b2.operate(new UnFlyWeight("第2次调用b。"));
}
}
// 享元接口
interface FlyWeight {
void operate(UnFlyWeight unFlyWeight);
}
// 具体享元
class SpecialFlyWeight implements FlyWeight {
private String key;
@Override
public void operate(UnFlyWeight unFlyWeight) {
System.out.print("具体享元" + key + "被调用,");
System.out.println("非享元信息是:" + unFlyWeight.getName());
}
public SpecialFlyWeight(String key) {
this.key = key;
}
}
// 享元工厂
class FlyWeightFactory {
private Map<String, FlyWeight> flyWeightMap = new HashMap<String, FlyWeight>();
FlyWeight getFlyWeight(String key) {
FlyWeight flyWeight = flyWeightMap.get(key);
if (flyWeight == null) {
SpecialFlyWeight specialFlyWeight = new SpecialFlyWeight(key);
flyWeightMap.put(key, specialFlyWeight);
return specialFlyWeight;
} else {
System.out.println("具体享元" + key + "已经存在,被成功获取!");
}
return flyWeight;
}
}
// 非享元对象
class UnFlyWeight {
private String name;
public UnFlyWeight(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
享元模式其实是工厂方法模式的一个改进机制,享元模式同样要求创建一个或一组对象,并且就是通过工厂方法模式生成对象的,只不过享元模式为工厂方法模式增加了缓存这一功能。
另外,在我看来,享元模式在某种程度上与多例有点像。
参考资料:
1.http://c.biancheng.net/view/1371.html
代码地址:https://gitee.com/zhoujie1/design-mode-and-principle.git