享元模式
运用共享技术有效地支持大量细粒度的对象。
享元模式结构图
享元类抽象类
/** * @author:shaoyongzhang * @date 2018/5/30 * @description */ public abstract class Flyweight { public abstract void operate(int extrinsicstate); }
共享享元类
/** * @author:shaoyongzhang * @date 2018/5/30 * @description */ public class SharedFlyweight extends Flyweight { @Override public void operate(int extrinsicstate) { System.out.println("共享类:外部状态:" + extrinsicstate); } }
非共享享元类
/** * @author:shaoyongzhang * @date 2018/5/30 * @description */ public class UnsharedFlyweight extends Flyweight { @Override public void operate(int extrinsicstate) { System.out.println("不共享类:外部状态:" + extrinsicstate); } }
享元工厂
/** * @author:shaoyongzhang * @date 2018/5/30 * @description */ public class FlyweightFactory { private static Hashtable<String, Flyweight> flyweightMap = new Hashtable<>(); public static Flyweight getFlyweight(String flag){ //先判断是否存在该对象 if (flyweightMap.containsKey(flag)) { return flyweightMap.get("flag"); } //创建对象放入map中 然后在返回 SharedFlyweight sharedFlyweight = new SharedFlyweight(); flyweightMap.put(flag,sharedFlyweight); return flyweightMap.get(flag); } }
客户端测试类
/** * @author:shaoyongzhang * @date 2018/5/30 * @description */ public class Client { public static void main(String[] args) { int extrinsicstate = 10; Flyweight sharedFlyweightA = FlyweightFactory.getFlyweight("A"); sharedFlyweightA.operate(extrinsicstate); Flyweight sharedFlyweightB = FlyweightFactory.getFlyweight("B"); sharedFlyweightB.operate(--extrinsicstate); Flyweight sharedFlyweightC = FlyweightFactory.getFlyweight("C"); sharedFlyweightC.operate(--extrinsicstate); UnsharedFlyweight unsharedFlyweight = new UnsharedFlyweight(); unsharedFlyweight.operate(--extrinsicstate); } }
输出结果
总结
享元模式可以避免大量的相似类的开销,在程序设计的时候,可能会有很多细粒度的类的实例来表示数据,如果这些数据中,只有少部分的数据是不同的,而其他的大部分数据基本上都是相同的时候,此时就可以使用享元模式,可以减少大量的需要实例化的对象。
在程序中,如果用了大量的对象,而这些对象又造成了存储开销的困难的时候就可以考虑使用,还有对象的大部分状态可以是外部状态,那么可以用相对较少的共享对象来取代很多对象,此时也可以使用享元模式。
用了享元模式,有了共享对象,实例化的对象会大大减少,内存开销就会更少,如果共享的越多,则减少的对象更多,节约的内存更多。