标签:src auto mode 部分 构造函数 open method target http
? Flyweight: 抽象享元类
? ConcreteFlyweight: 具体享元类
? UnsharedConcreteFlyweight: 非共享具体享元类
? FlyweightFactory: 享元工厂类
1 /** 2 * Flyweight 3 * 抽象享元类 4 */ 5 public interface Flyweight { 6 //一个示意性方法,参数state是外蕴状态 7 public void operation(String state); 8 } 9 10 /** 11 * ConcreteFlyweight 12 * 具体享元类 13 */ 14 public class ConcreteFlyweight implements Flyweight { 15 //代表内部状态 16 private Character intrinsicState = null; 17 /** 18 * 构造函数,内蕴状态作为参数传入 19 * @param state 20 */ 21 public ConcreteFlyweight(Character state){ 22 this.intrinsicState = state; 23 } 24 25 26 /** 27 * 外蕴状态作为参数传入方法中,改变方法的行为, 28 * 但是并不改变对象的内蕴状态。 29 */ 30 @Override 31 public void operation(String state) { 32 // TODO Auto-generated method stub 33 System.out.println("Intrinsic State = " + this.intrinsicState); 34 System.out.println("Extrinsic State = " + state); 35 } 36 37 } 38 39 /** 40 * FlyweightFactory 41 * 享元工厂类 42 */ 43 public class FlyweightFactory { 44 private Map<Character,Flyweight> files = new HashMap<Character,Flyweight>(); 45 46 public Flyweight factory(Character state){ 47 //先从缓存中查找对象 48 Flyweight fly = files.get(state); 49 if(fly == null){ 50 //如果对象不存在则创建一个新的Flyweight对象 51 fly = new ConcreteFlyweight(state); 52 //把这个新的Flyweight对象添加到缓存中 53 files.put(state, fly); 54 } 55 return fly; 56 } 57 } 58 59 /** 60 * client 61 */ 62 public class Client { 63 64 public static void main(String[] args) { 65 // TODO Auto-generated method stub 66 FlyweightFactory factory = new FlyweightFactory(); 67 Flyweight fly = factory.factory(new Character(‘a‘)); 68 fly.operation("First Call"); 69 70 fly = factory.factory(new Character(‘b‘)); 71 fly.operation("Second Call"); 72 73 fly = factory.factory(new Character(‘a‘)); 74 fly.operation("Third Call"); 75 } 76 77 }
标签:src auto mode 部分 构造函数 open method target http
原文地址:https://www.cnblogs.com/756623607-zhang/p/9227072.html