一、介绍
享元模式(Flyweight),运用共享技术有效地支持大量细粒度的对象。
元模式可以避免大量非常相似类的开销。在程序设计中,有时需要生成大量细粒度的类实例来表示数据。如果能发现这些实例除了几个参数外基本上都是相同的,有时就能够大幅度地减少需要实例化的类的数量。如果能把那些参数移到类实例的外面,在方法调用时将它们传递进来,就可以通过共享大幅度地减少单个实例的数目。
二、代码实现
public abstract class Flyweight { public abstract void operation(int extrinsicstate); } //需要共享的具体Flyweight子类 public class ConcreteFlyweight extends Flyweight{ @Override public void operation(int extrinsicstate) { System.out.println("具体Flyweight"+extrinsicstate); } } //不需要共享的具体Flyweight子类 public class UnsharedConcreteFlyweight extends Flyweight{ @Override public void operation(int extrinsicstate) { System.out.println("不共享的具体Flyweight"+extrinsicstate); } } public class FlywdightFactory { private Hashtable<String,Flyweight> flyweights=new Hashtable<>(); public FlywdightFactory() { flyweights.put("X",new ConcreteFlyweight()); flyweights.put("Y",new ConcreteFlyweight()); flyweights.put("Z",new ConcreteFlyweight()); } public Flyweight getFlyweighty(String key) { return (Flyweight)flyweights.get(key); } }
public class Client { public static void main(String[] args) { int extrinsicstate = 22; FlywdightFactory factory = new FlywdightFactory(); Flyweight fx = factory.getFlyweighty("X"); fx.operation(--extrinsicstate); Flyweight fy = factory.getFlyweighty("Y"); fy.operation(--extrinsicstate); Flyweight fz = factory.getFlyweighty("Z"); fz.operation(--extrinsicstate); Flyweight uf = new UnsharedConcreteFlyweight(); uf.operation(--extrinsicstate); } }