标签:
结构 | |
意图 | 运用共享技术有效地支持大量细粒度的对象。 |
适用性 |
|
1 using System; 2 using System.Collections; 3 4 class FlyweightFactory 5 { 6 private ArrayList pool = new ArrayList(); 7 8 // the flyweightfactory can crete all entries in the pool at startup 9 // (if the pool is small, and it is likely all will be used), or as 10 // needed, if the pool si large and it is likely some will never be used 11 public FlyweightFactory() 12 { 13 pool.Add(new ConcreteEvenFlyweight()); 14 pool.Add(new ConcreteUnevenFlyweight()); 15 } 16 17 public Flyweight GetFlyweight(int key) 18 { 19 // here we would determine if the flyweight identified by key 20 // exists, and if so return it. If not, we would create it. 21 // As in this demo we have implementation all the possible 22 // flyweights we wish to use, we retrun the suitable one. 23 int i = key % 2; 24 return((Flyweight)pool[i]); 25 } 26 } 27 28 abstract class Flyweight 29 { 30 abstract public void DoOperation(int extrinsicState); 31 } 32 33 class UnsharedConcreteFlyweight : Flyweight 34 { 35 override public void DoOperation(int extrinsicState) 36 { 37 38 } 39 } 40 41 class ConcreteEvenFlyweight : Flyweight 42 { 43 override public void DoOperation(int extrinsicState) 44 { 45 Console.WriteLine("In ConcreteEvenFlyweight.DoOperation: {0}", extrinsicState); 46 } 47 } 48 49 class ConcreteUnevenFlyweight : Flyweight 50 { 51 override public void DoOperation(int extrinsicState) 52 { 53 Console.WriteLine("In ConcreteUnevenFlyweight.DoOperation: {0}", extrinsicState); 54 } 55 } 56 57 /// <summary> 58 /// Summary description for Client. 59 /// </summary> 60 public class Client 61 { 62 public static int Main(string[] args) 63 { 64 int[] data = {1,2,3,4,5,6,7,8}; 65 66 FlyweightFactory f = new FlyweightFactory(); 67 68 int extrinsicState = 3; 69 foreach (int i in data) 70 { 71 Flyweight flyweight = f.GetFlyweight(i); 72 flyweight.DoOperation(extrinsicState); 73 } 74 75 return 0; 76 } 77 }
标签:
原文地址:http://www.cnblogs.com/ziranquliu/p/4663323.html