结构型设计模式之享元模式(Flyweight)

结构
意图 运用共享技术有效地支持大量细粒度的对象。
适用性
  • 一个应用程序使用了大量的对象。
  • 完全由于使用大量的对象,造成很大的存储开销。
  • 对象的大多数状态都可变为外部状态。
  • 如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象。
  • 应用程序不依赖于对象标识。由于F l y w e i g h t 对象可以被共享,对于概念上明显有别的对象,标识测试将返回真值。

 

 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     }
享元模式

 

posted @ 2015-07-21 08:37  自然去留  阅读(178)  评论(0编辑  收藏  举报