一.什么是享元模式
享元模式就是减少对象的创建以此来减少内存占用,提高性能。也是种结构性设计模式。
二.理解享元模式
通过享元模式的概念相信就很容易理解,无非就是使用缓存的,不去重复创建对象,下面來看看UML类图
代码实现
public abstract class FlyWeight {
protected abstract void operate();
}
public class ConcreteFlyWeight extends FlyWeight {
@Override
protected void operate() {
System.out.println("shared");
}
}
public class UnSharedFlyWeight extends FlyWeight{
@Override
protected void operate() {
System.out.println("unshared");
}
}
public class FlyWeightFactory {
HashMap<String, FlyWeight> flyWeights=new HashMap<String, FlyWeight>();
public FlyWeight getFlyWeight(String key) {
if(!flyWeights.containsKey(key)) {
flyWeights.put(key, new ConcreteFlyWeight());
}
return (FlyWeight)flyWeights.get(key);
}
}
客户端调用
public class Client {
public static void main(String[] args) {
FlyWeightFactory flyWeightFactory=new FlyWeightFactory();
System.out.println(flyWeightFactory.getFlyWeight("a"));
System.out.println(flyWeightFactory.getFlyWeight("a"));
}
}
打印结果:
com.seven.flyweight.ConcreteFlyWeight@15db9742
com.seven.flyweight.ConcreteFlyWeight@15db9742
都是同一个对象,享元模式还可以在模板中的方法中加入外部可变对象,这样我们返回的共享实例对象,只要Key值是唯一,返回的对象不会重新创建,但是可以操控不同的对象,这个外部对象的方法就是外部状态。
三.小结
享元模式最大的优点就是共享对象,增加内存利用率,一般都是在缓存中使用。