文章出處

索引

意圖

運用共享技術有效地支持大量細粒度的對象。

Use sharing to support large numbers of fine-grained objects efficiently.

結構

下面的對象圖說明了如何共享 Flyweight:

參與者

Flyweight

  • 描述一個接口,通過這個接口 Flyweight 可以接受并作用于外部狀態。

ConcreteFlyweight

  • 實現 Flyweight 接口,并為內部狀態增加存儲空間。該對象必須是可共享的。它所存儲的狀態必須是內部的,即必須獨立于對象的場景。

UnsharedConcreteFlyweight

  • 并非所有的 Flyweight 子類都需要被共享。Flyweight 接口使共享成為可能,但它并不強制共享。

FlyweightFactory

  • 創建并管理 Flyweight 對象。
  • 確保合理地共享 Flyweight。

Client

  • 維持一個對 Flyweight 的引用。
  • 計算或存儲 Flyweight 的外部狀態。

適用性

Flyweight 模式的有效性很大程度上取決于如何使用它以及在何處使用它。

當以下情況成立時可以使用 Flyweight 模式:

  • 一個應用程序使用了大量的對象。
  • 完全由于使用大量對象,造成很大的存儲開銷。
  • 對象的大多數狀態都可變為外部狀態。
  • 如果刪除對象的外部狀態,那么可以用相對較少的共享對象取代很多組對象。
  • 應用程序不依賴于對象標識。

效果

  • 存儲空間上的節省抵消了傳輸、查找和計算外部狀態時的開銷。節約量隨著共享狀態的增多而增大。

相關模式

  • Flyweight 模式通常和 Composite 模式結合起來,用共享葉節點的又向無環圖實現一個邏輯上的層次結構。
  • 通常,最好用 Flyweight 實現 State 和 Strategy 對象。

實現

實現方式(一):使用 FlyweightFactory 管理 Flyweight 對象。

Flyweight 模式的可用性在很大程度上取決于是否易識別外部狀態并將它從共享對象中刪除。

理想的狀況是,外部狀態可以由一個單獨的對象結構計算得到,且該結構的存儲要求非常小。

通常,因為 Flyweight 對象是共享的,用戶不能直接對它進行實例化,因為 FlyweightFactory 可以幫助用戶查找某個特定的 Flyweight 對象。

共享還意味著某種形式的引用計數和垃圾回收。

 1 namespace FlyweightPattern.Implementation1
 2 {
 3   public abstract class Flyweight
 4   {
 5     public abstract string Identifier { get; }
 6     public abstract void Operation(string extrinsicState);
 7   }
 8 
 9   public class ConcreteFlyweight : Flyweight
10   {
11     public override string Identifier
12     {
13       get { return "hello"; }
14     }
15 
16     public override void Operation(string extrinsicState)
17     {
18       // do something
19     }
20   }
21 
22   public class FlyweightFactory
23   {
24     private Dictionary<string, Flyweight> _pool
25       = new Dictionary<string, Flyweight>();
26 
27     public Flyweight CreateFlyweight(string identifier)
28     {
29       if (!_pool.ContainsKey(identifier))
30       {
31         Flyweight flyweight = new ConcreteFlyweight();
32         _pool.Add(flyweight.Identifier, flyweight);
33       }
34 
35       return _pool[identifier];
36     }
37   }
38 
39   public class Client
40   {
41     public void TestCase1()
42     {
43       FlyweightFactory factory = new FlyweightFactory();
44       Flyweight flyweight1 = factory.CreateFlyweight("hello");
45       Flyweight flyweight2 = factory.CreateFlyweight("hello");
46       flyweight1.Operation("extrinsic state");
47       flyweight2.Operation("extrinsic state");
48     }
49   }
50 }

設計模式之美》為 Dennis Gao 發布于博客園的系列文章,任何未經作者本人同意的人為或爬蟲轉載均為耍流氓。


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()