设计模式——享元模式
| 名称 | Flyweight |
| 结构 | ![]() |
| 意图 | 运用共享技术有效地支持大量细粒度的对象。 |
| 适用性 |
|
| Code Example |
1 // Flyweight2 ![]() 3 // Intent: "Use sharing to support large numbers of fine-grained objects effectively". 4 ![]() 5 // For further information, read "Design Patterns", p195, Gamma et al.,6 // Addison-Wesley, ISBN:0-201-63361-27 ![]() 8 /* Notes:9 * Useful patetn when you have a small(ish) number of objects that might be 10 * needed a very large number of times - with slightly differnt informaiton,11 * that can be externalised outside those objects. 12 */13 14 namespace Flyweight_DesignPattern15 {16 using System;17 using System.Collections;18 ![]() 19 class FlyweightFactory 20 {21 private ArrayList pool = new ArrayList();22 ![]() 23 // the flyweightfactory can crete all entries in the pool at startup 24 // (if the pool is small, and it is likely all will be used), or as 25 // needed, if the pool si large and it is likely some will never be used26 public FlyweightFactory()27 {28 pool.Add(new ConcreteEvenFlyweight()); 29 pool.Add(new ConcreteUnevenFlyweight()); 30 }31 ![]() 32 public Flyweight GetFlyweight(int key)33 {34 // here we would determine if the flyweight identified by key 35 // exists, and if so return it. If not, we would create it. 36 // As in this demo we have implementation all the possible 37 // flyweights we wish to use, we retrun the suitable one. 38 int i = key % 2;39 return((Flyweight)pool[i]); 40 }41 }42 ![]() 43 abstract class Flyweight 44 {45 abstract public void DoOperation(int extrinsicState); 46 }47 ![]() 48 class UnsharedConcreteFlyweight : Flyweight49 {50 override public void DoOperation(int extrinsicState)51 {52 53 }54 }55 ![]() 56 class ConcreteEvenFlyweight : Flyweight57 {58 override public void DoOperation(int extrinsicState)59 {60 Console.WriteLine("In ConcreteEvenFlyweight.DoOperation: {0}", extrinsicState); 61 }62 }63 ![]() 64 class ConcreteUnevenFlyweight : Flyweight65 {66 override public void DoOperation(int extrinsicState)67 {68 Console.WriteLine("In ConcreteUnevenFlyweight.DoOperation: {0}", extrinsicState); 69 } 70 }71 ![]() 72 /// <summary>73 /// Summary description for Client.74 /// </summary>75 public class Client76 {77 public static int Main(string[] args)78 {79 int[] data = {1,2,3,4,5,6,7,8};80 81 FlyweightFactory f = new FlyweightFactory();82 83 int extrinsicState = 3;84 foreach (int i in data)85 {86 Flyweight flyweight = f.GetFlyweight(i);87 flyweight.DoOperation(extrinsicState);88 }89 90 return 0;91 }92 }93 }94 ![]() 95 ![]() |






* Useful patetn when you have a small(ish) number of objects that might be


}
浙公网安备 33010602011771号