享元模式:运用共享技术有效地支持大量细粒度的对象.
内部状态和外部状态:
享元模式可以避免大量的非常相似的类的开销.在程序设计中,有时需要生成大量细粒度的类实例来表示数据.如果能发现这些实例除了几个参数外基本上都相同,有时就能大幅度减少需要实例化的类的数量.如果能把那些参数移到类实例的外部,在方法调用时将它们传递进来,就可以通过共享,大幅度地减少单个实例的数目.
何时使用享元模式:
如果一个应用程序使用了大量的对象,而大量的这些对象造成了存储开销时就应该考虑使用;还有就是对象的部分状态可已放到外部,那就可以用较少的共享对象来表示很多组对象.
享元模式结构图:
代码实现:
1 package com.cgj.pattern.flyweight; 2 3 /** 4 * Flyweight接口:是多有享元类的超类或接口,通过这个接口, 5 * Flyweight可以接受并作用于外部状态. 6 */ 7 public interface Flyweight { 8 9 public abstract void operation(int extrinsicstate); 10 }
1 package com.cgj.pattern.flyweight; 2 3 /** 4 * ConcreteFlyweight类实现Flyweight接口,并为内部状态增加存储空间. 5 */ 6 public class ConcreteFlyweight implements Flyweight { 7 8 @Override 9 public void operation(int extrinsicstate) { 10 System.out.println("具体的Flyweight:" + extrinsicstate); 11 } 12 13 }
1 package com.cgj.pattern.flyweight; 2 3 /** 4 * UnsharedConcreteFlyweight指不需要共享的Flyweight实现类. 5 * 因为实现了Flyweight接口共享成为可能,但并不强制共享. 6 */ 7 public class UnsharedConcreteFlyweight implements Flyweight { 8 9 @Override 10 public void operation(int extrinsicstate) { 11 System.out.println("不共享的具体Flyweight:" + extrinsicstate); 12 } 13 14 }
1 package com.cgj.pattern.flyweight; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 6 /** 7 * Flyweight是一个享元工厂,用来创建并管理Flyweight类对象. 8 * 它主要用来确保合理的共享Flyweight,当用户请求一个Flyweight时, 9 * 它创建一个Flyweight或者返回一个已经创建好的Flyweight. 10 */ 11 public class FlyweightFactory { 12 13 // 保存Flyweight 14 private Map<String, Flyweight> flyweights = new HashMap<String, Flyweight>(); 15 16 // 获取Flyweight 17 public Flyweight getFlyweight(String key) { 18 if (!flyweights.containsKey(key)) { 19 flyweights.put(key, new ConcreteFlyweight()); 20 } 21 return flyweights.get(key); 22 } 23 24 }
1 package com.cgj.pattern.flyweight; 2 3 public class Test { 4 5 public static void main(String[] args) { 6 int extrinsicstate = 22; 7 8 FlyweightFactory factory = new FlyweightFactory(); 9 10 Flyweight fx = factory.getFlyweight("X"); 11 fx.operation(extrinsicstate--); 12 13 Flyweight fy = factory.getFlyweight("Y"); 14 fy.operation(extrinsicstate--); 15 16 Flyweight fz = factory.getFlyweight("Z"); 17 fz.operation(extrinsicstate--); 18 19 Flyweight uf = new UnsharedConcreteFlyweight(); 20 uf.operation(extrinsicstate); 21 } 22 23 }
(本随笔参考了 程杰老师的 <<大话设计模式>>)