享元模式(Flyweigh),运用共享技术有效地支持大量细粒度的对象。
package flyweight;//可以接受并作用于外部状态 public abstract class Flyweight {public abstract void operation(int extrinsicState);}
package flyweight;//为内部状态增加存储空间 public class ConcreteFlyweight extends Flyweight{@Overridepublic void operation(int extrinsicState) {System.out.println("ConcreteFlyweight"+extrinsicState);}}
package flyweight;//不需要共享的子类 public class UnsharedConcreteFlyweight extends Flyweight {@Overridepublic void operation(int extrinsicState) {System.out.println("UnsharedConcreteFlyweight"+extrinsicState);}}
package flyweight;import java.util.HashMap;public class FlyweightFactory {private HashMap<String, Flyweight> flyweightMap=new HashMap<String, Flyweight>();public FlyweightFactory() {flyweightMap.put("X", new ConcreteFlyweight());flyweightMap.put("Y", new ConcreteFlyweight());flyweightMap.put("Z", new ConcreteFlyweight());}public Flyweight getFlyweightMap(String key) {return flyweightMap.get(key);}public static void main(String[] args) {int extrinsicState=22;FlyweightFactory flyweightFactory=new FlyweightFactory();Flyweight flyweight=flyweightFactory.getFlyweightMap("X");flyweight.operation(--extrinsicState);Flyweight flyweight2=flyweightFactory.getFlyweightMap("Y");flyweight.operation(--extrinsicState);Flyweight flyweight3=flyweightFactory.getFlyweightMap("Z");flyweight.operation(--extrinsicState);UnsharedConcreteFlyweight unsharedConcreteFlyweight=new UnsharedConcreteFlyweight();unsharedConcreteFlyweight.operation(--extrinsicState);}}
享元模式可以避免大量非常相似类的开销。在程序设计中,有时需要生成大量细粒度的类实例来表示数据。如果能发现这些实例除了几个参数外基本上都是相同的,有时就能够大幅度地减少需要实例化的类的数量,如果能把那些参数移到类实例的外面,在方法调用时将它们传递进来,就可以通过共享大幅度地减少单个实例的数目。