享元模式
享元模式是对象的结构模式。享元模式以共享的方式高效地支持大量的细粒度对象。
1 import java.util.HashMap; 2 import java.util.Map; 3 4 //抽象享元接口 5 interface Flyweight{ 6 //state参数为外蕴状态 7 public void method(String state); 8 } 9 10 //具体享元类 11 class ConcreteFlyweight implements Flyweight{ 12 13 private String inState; 14 15 //内蕴状态作为参数传入 16 public ConcreteFlyweight(String inState){ 17 this.inState = inState; 18 } 19 20 @Override 21 public void method(String state) { 22 System.out.println("外蕴状态" + state); 23 System.out.println("内蕴状态" + inState); 24 } 25 26 } 27 28 //享元工厂类 29 class FlyweightFactory{ 30 31 private Map<String, Flyweight> flies = new HashMap<String, Flyweight>(); 32 33 public Flyweight factory(String inState){ 34 //从缓存中查询有没有指定的变量 35 Flyweight fly = flies.get(inState); 36 if(null == fly){ 37 fly = new ConcreteFlyweight(inState); 38 flies.put(inState, fly); 39 } 40 return fly; 41 } 42 }