设计模式 享元模式(Flyweight)

时间:2022-09-03 19:49:05

意图

  运用共享技术有效地支持大量细粒度的对象。典型的享元模式的例子为文书处理器中以图形结构来表示字符。一个做法是,每个字型有其字型外观, 字模 metrics, 和其它格式资讯,但这会使每个字符就耗用上千字节。取而代之的是,每个字符参照到一个共享字形物件,此物件会被其它有共同特质的字符所分享;只有每个字符(文件中或页面中)的位置才需要另外储存。以下程式用来解释上述的文件例子。这个例子用来解释享元模式利用只载立执行立即小任务所必需的资料,因而减少内存使用量。 

适用性

  1.一个应用程序使用了大量的对象。

  2.完全由于使用大量的对象,造成很大的存储开销。

  3.对象的大多数状态都可变为外部状态。

  4.如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象。

  5.应用程序不依赖于对象标识。由于F l y w e i g h t 对象可以被共享,对于概念上明显有别的对象,标识测试将返回真值。 

结构图

设计模式 享元模式(Flyweight)

Code

 

 1 // Flyweight
2
3 /* Notes:
4 * Useful patetn when you have a small(ish) number of objects that might be
5 * needed a very large number of times - with slightly differnt informaiton,
6 * that can be externalised outside those objects.
7 */
8
9 namespace Flyweight_DesignPattern
10 {
11 using System;
12 using System.Collections;
13
14 class FlyweightFactory
15 {
16 private ArrayList pool = new ArrayList();
17
18 // the flyweightfactory can crete all entries in the pool at startup
19 // (if the pool is small, and it is likely all will be used), or as
20 // needed, if the pool si large and it is likely some will never be used
21 public FlyweightFactory()
22 {
23 pool.Add(new ConcreteEvenFlyweight());
24 pool.Add(new ConcreteUnevenFlyweight());
25 }
26
27 public Flyweight GetFlyweight(int key)
28 {
29 // here we would determine if the flyweight identified by key
30 // exists, and if so return it. If not, we would create it.
31 // As in this demo we have implementation all the possible
32 // flyweights we wish to use, we retrun the suitable one.
33 int i = key % 2;
34 return((Flyweight)pool[i]);
35 }
36 }
37
38 abstract class Flyweight
39 {
40 abstract public void DoOperation(int extrinsicState);
41 }
42
43 class UnsharedConcreteFlyweight : Flyweight
44 {
45 override public void DoOperation(int extrinsicState)
46 {
47
48 }
49 }
50
51 class ConcreteEvenFlyweight : Flyweight
52 {
53 override public void DoOperation(int extrinsicState)
54 {
55 Console.WriteLine("In ConcreteEvenFlyweight.DoOperation: {0}", extrinsicState);
56 }
57 }
58
59 class ConcreteUnevenFlyweight : Flyweight
60 {
61 override public void DoOperation(int extrinsicState)
62 {
63 Console.WriteLine("In ConcreteUnevenFlyweight.DoOperation: {0}", extrinsicState);
64 }
65 }
66
67 /// <summary>
68 /// Summary description for Client.
69 /// </summary>
70 public class Client
71 {
72 public static int Main(string[] args)
73 {
74 int[] data = {1,2,3,4,5,6,7,8};
75
76 FlyweightFactory f = new FlyweightFactory();
77
78 int extrinsicState = 3;
79 foreach (int i in data)
80 {
81 Flyweight flyweight = f.GetFlyweight(i);
82 flyweight.DoOperation(extrinsicState);
83 }
84
85 return 0;
86 }
87 }
88 }