Flyweight Pattern

設計模式 - Flyweight Pattern. 使用共享技術來支持對細粒度對象的高效使用

基本介紹

  • 中文名:享元模式
  • 外文名:Flyweight Pattern
定義,類圖,參與者,實例代碼,

定義

使用共享技術來支持對細粒度對象的高效使用.

類圖

Flyweight Pattern

參與者

如下類和對象參與到Flyweight模式中:
  • Flyweight(Character)
  • 聲明一個接口,flyweights通過這個接口來接收和處理外部狀態.
ConcreteFlyweight(CharacterA, CharacterB, ..., CharacterZ)
  • 實現Flyweight的接口,如果必要的話,為內部狀態分配存儲.一個具體的Flyweight對象必須是可共享的.任何存儲的狀態必須是內部的,也就是說,內部狀態必須獨立於具體Flyweight對象的上下文.
UnsharedConcreteFlyweight( not used )
  • 並不是所有的Flyweight子類都需要共享.共享是通過接口來實現的,但是不是必須實現接口提供共享.在Flyweight對象結構中,非共享的Flyweight對象可以有具體的子類對象.
FlyweightFactory(CharacterFactory)
  • Flyweight工廠用來創建,管理flyweight對象.
  • 保證正確的共享flyweight.當客戶client請求一個flyweight對象的時候, Flyweight工廠對象會提供一個已經存在的對象實例給客戶,如果這個對象實例不存在,則會創建一個.
Client(FlyweightApp)
  • 維護一個對flyweight的引用.
  • 計算或者存儲flyweight的外部狀態.

實例代碼

這一段代碼演示了一個Flyweight模板. 在代碼中,一些相等小數量的對象被不同的客戶多次共享.
usingSystem;usingSystem.Collections;namespaceDoFactory.GangOfFour.Flyweight.Structural{///<summary>///MainAppstartupclassforStructural///FlyweightDesignPattern.///</summary>classMainApp{///<summary>///Entrypointintoconsoleapplication.///</summary>staticvoidMain(){//Arbitraryextrinsicstateintextrinsicstate=22;FlyweightFactoryfactory=newFlyweightFactory();//WorkwithdifferentflyweightinstancesFlyweightfx=factory.GetFlyweight("X");fx.Operation(--extrinsicstate);Flyweightfy=factory.GetFlyweight("Y");fy.Operation(--extrinsicstate);Flyweightfz=factory.GetFlyweight("Z");fz.Operation(--extrinsicstate);UnsharedConcreteFlyweightfu=newUnsharedConcreteFlyweight();fu.Operation(--extrinsicstate);//WaitforuserConsole.ReadKey();}}///<summary>///The'FlyweightFactory'class///</summary>classFlyweightFactory{privateHashtableflyweights=newHashtable();//ConstructorpublicFlyweightFactory(){flyweights.Add("X",newConcreteFlyweight());flyweights.Add("Y",newConcreteFlyweight());flyweights.Add("Z",newConcreteFlyweight());}publicFlyweightGetFlyweight(stringkey){return((Flyweight)flyweights[key]);}}///<summary>///The'Flyweight'abstractclass///</summary>abstractclassFlyweight{publicabstractvoidOperation(intextrinsicstate);}///<summary>///The'ConcreteFlyweight'class///</summary>classConcreteFlyweight:Flyweight{publicoverridevoidOperation(intextrinsicstate){Console.WriteLine("ConcreteFlyweight:"+extrinsicstate);}}///<summary>///The'UnsharedConcreteFlyweight'class///</summary>classUnsharedConcreteFlyweight:Flyweight{publicoverridevoidOperation(intextrinsicstate){Console.WriteLine("UnsharedConcreteFlyweight:"+extrinsicstate);}}}
輸出
ConcreteFlyweight:21ConcreteFlyweight:20ConcreteFlyweight:19UnsharedConcreteFlyweight:18

相關詞條

熱門詞條

聯絡我們