享元模式(Flyweight) 运用共享技术有效地支持大量细粒度的对象
使用场景:
如果一个应用程序使用了大量的对象,而大量的对象造成了很大的存储开销时就应该考虑使用;还有就是对象的
大多数状态可以外部状态,如果删除对象的外部状态,那么就可以用相对较少的共享对象取代很多组对象,
此时就可以考虑享元模式
使用好处:
享元模式可以避免大量非常类似的开销。再程序设计中,有时需要生成大量细粒度的类实例来表示数据。
如果发现这些实列除了几个参数外基本上都相同,有时就能够大幅度的减少需要实例化的类的数量。如果
把这些参数移到类实例的外面,在方法调用时将它们传递进来,就可以通过共享大幅度的减少单个实例的个数。
实现代码如下:
1 public abstract class Flyweight { 2 public abstract void operation(int extrinsicstate); 3 }
1 public class ConcreteFlyweight extends Flyweight{ 2 3 @Override 4 public void operation(int extrinsicstate) { 5 System.out.println("具体实现Flyweight--》"+extrinsicstate); 6 7 } 8 9 }
1 public class UnSharedConcreteFlyweight extends Flyweight{ 2 3 @Override 4 public void operation(int extrinsicstate) { 5 System.out.println("不共享具体实现Flyweight--》"+extrinsicstate); 6 7 } 8 9 }
1 import com.sun.org.apache.xalan.internal.xsltc.runtime.Hashtable; 2 3 public class FlyweightFactory { 4 private Hashtable flyweights = new Hashtable(); 5 6 public FlyweightFactory() { 7 flyweights.put("x", new ConcreteFlyweight()); 8 flyweights.put("y", new ConcreteFlyweight()); 9 flyweights.put("z", new ConcreteFlyweight()); 10 } 11 12 public Flyweight getFlyweight(String key){ 13 return (Flyweight) flyweights.get(key); 14 } 15 16 }
1 public class FlyweightTest { 2 public static void main(String[] args) { 3 int extrinsicstate = 22; 4 FlyweightFactory f = new FlyweightFactory(); 5 6 ConcreteFlyweight fx = (ConcreteFlyweight) f.getFlyweight("x"); 7 fx.operation(--extrinsicstate); 8 9 ConcreteFlyweight fy = (ConcreteFlyweight) f.getFlyweight("y"); 10 fy.operation(--extrinsicstate); 11 12 ConcreteFlyweight fz = (ConcreteFlyweight) f.getFlyweight("z"); 13 fz.operation(--extrinsicstate); 14 15 UnSharedConcreteFlyweight uf = new UnSharedConcreteFlyweight(); 16 uf.operation(--extrinsicstate); 17 } 18 }
具体实现Flyweight--》21 具体实现Flyweight--》20 具体实现Flyweight--》19 不共享具体实现Flyweight--》18