享元模式
运用共享技术有效的支持大量细粒度的对象。
FlyWeight
package com.hml.flyweight; public abstract class FlyWeight { public abstract void operation(int p); }
ConcreateFlyWeight
package com.hml.flyweight; public class ConcreateFlyWeight extends FlyWeight { @Override public void operation(int p) { System.out.println("具体的类:" + p); } }
FlyWeigthFactory
package com.hml.flyweight; import java.util.HashMap; import java.util.Map; public class FlyWeigthFactory { private static Map<String, FlyWeight> flyweigths = new HashMap<String, FlyWeight>(); static { flyweigths.put("x", new ConcreateFlyWeight()); flyweigths.put("y", new ConcreateFlyWeight()); flyweigths.put("z", new ConcreateFlyWeight()); } public static FlyWeight getFlyWeight(String key) { return flyweigths.get(key); } }
Test
package com.hml.flyweight; public class Test { public static void main(String[] args) { FlyWeigthFactory factory = new FlyWeigthFactory(); FlyWeight f = factory.getFlyWeight("x"); f.operation(22); f = factory.getFlyWeight("y"); f.operation(22); } }
类图
享元模式可以避免大量非常相似类的开销。在程序设计中,有时需要生成大量细粒度的类的实例来表示数据。如果能发现这些实例除了几个参数外基本上相同,有时就能够大幅度的减少需要实例化的类的数量。如果能把参数移到类的外面,在方法调用时传递进来,就可以可以通过共享减少单个实例的数据量。