享元模式(Flyweight)

享元模式:应用共享技术有效支持大量细粒度的对象。

 1 namespace FlyWeightPattern
 2 {
 3     //2017.07.01 14:22 by ldb
 4     //享元基类
 5     abstract class FlyWeight
 6     {
 7         public abstract void Operation(int extrinsicstate);
 8     }
 9 
10     class ConcreteFlyWeight : FlyWeight
11     {
12         public override void Operation(int extrinsicstate)
13         {
14             Console.WriteLine("具体FlyWeight:" + extrinsicstate);
15         }
16     }
17     /// <summary>
18     /// 不需要共享的FlyWeight子类
19     /// </summary>
20     class UshareConcreteFlyWeight : FlyWeight
21     {
22         public override void Operation(int extrinsicstate)
23         {
24             Console.WriteLine("不共享的具体FlyWeight:" + extrinsicstate);
25         }
26     }
27 
28     class FlyWeightFactory//享元工厂。
29     {
30         private Hashtable flyweights = new Hashtable();
31 
32         public FlyWeightFactory()
33         {
34             flyweights.Add("x", new ConcreteFlyWeight());
35             flyweights.Add("y", new ConcreteFlyWeight());
36             flyweights.Add("", new ConcreteFlyWeight());
37         }
38 
39         public FlyWeight GetFlyWeight(string key)
40         {
41             return (FlyWeight)flyweights[key];
42         }
43     }
44     class Program
45     {
46         static void Main(string[] args)
47         {
48             int extrinsicstate = 22;
49 
50             FlyWeightFactory fact = new FlyWeightFactory();
51 
52             FlyWeight fx = fact.GetFlyWeight("x");
53             fx.Operation(--extrinsicstate);
54 
55             FlyWeight fy = fact.GetFlyWeight("y");
56             fy.Operation(--extrinsicstate);
57 
58             FlyWeight uf = new UshareConcreteFlyWeight();
59             uf.Operation(--extrinsicstate);
60 
61             Console.ReadKey();
62         }
63     }
64 }

 

posted @ 2017-07-01 14:32  longdb  阅读(89)  评论(0)    收藏  举报