标签:
运用共享技术有效的支持大量细粒度的对象。
package com.hml.flyweight; public abstract class FlyWeight { public abstract void operation(int p); }
package com.hml.flyweight; public class ConcreateFlyWeight extends FlyWeight { @Override public void operation(int p) { System.out.println("具体的类:" + p); } }
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); } }
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); } }
享元模式可以避免大量非常相似类的开销。在程序设计中,有时需要生成大量细粒度的类的实例来表示数据。如果能发现这些实例除了几个参数外基本上相同,有时就能够大幅度的减少需要实例化的类的数量。如果能把参数移到类的外面,在方法调用时传递进来,就可以可以通过共享减少单个实例的数据量。
标签:
原文地址:http://www.cnblogs.com/heml/p/4656709.html