C#設計模式(11)-Composite Pattern

 ----------http://www.cnblogs.com/zhenyulu/articles/41829.html

一、 合成(Composite)模式

合成模式有時又叫做部分-整體模式(Part-Whole)。合成模式將對象組織到樹結構中,可以用來描述整體與部分的關係。合成模式可以使客戶端將單純元素與複合元素同等看待。

從和尚的故事談起

這是小時候我奶奶講的故事:從前有個山,山裏有個廟,廟裏有個老和尚在給小和尚講故事,講的什麼故事呢?從前有個山,山裏有個廟……。奶奶的故事要循環多少次,根據你多長時間睡着而定。在故事中有山、有廟、有和尚、有故事。因此,故事的角色有兩種:一種裏面沒有其它角色;另一種內部有其它角色。

對象的樹結構

一個樹結構由兩種節點組成:樹枝節點和樹葉節點。樹枝節點可以有子節點,而一個樹葉節點不可以有子節點。除了根節點外,其它節點有且只有一個父節點。

注意:一個樹枝節點可以不帶任何葉子,但是它因爲有帶葉子的能力,因此仍然是樹枝節點,而不會成爲葉節點。一個樹葉節點永遠不可能帶有子節點。


二、 合成模式概述

下圖所示的類圖省略了各個角色的細節。

 Pic59.gif

可以看出,上面的類圖結構涉及到三個角色:

  • 抽象構件(Component)角色:這是一個抽象角色,它給參與組合的對象規定一個接口。這個角色給出共有接口及其默認行爲。
  • 樹葉構件(Leaf)角色:代表參加組合的樹葉對象。一個樹葉對象沒有下級子對象。
  • 樹枝構件(Composite)角色:代表參加組合的有子對象的對象,並給出樹枝構件對象的行爲。

可以看出,Composite類型的對象可以包含其它Component類型的對象。換而言之,Composite類型對象可以含有其它的樹枝(Composite)類型或樹葉(Leaf)類型的對象。

合成模式的實現根據所實現接口的區別分爲兩種形式,分別稱爲安全模式和透明模式。合成模式可以不提供父對象的管理方法,但合成模式必須在合適的地方提供子對象的管理方法(諸如:add、remove、getChild等)。

透明方式

作爲第一種選擇,在Component裏面聲明所有的用來管理子類對象的方法,包括add()、remove(),以及getChild()方法。這樣做的好處是所有的構件類都有相同的接口。在客戶端看來,樹葉類對象與合成類對象的區別起碼在接口層次上消失了,客戶端可以同等同的對待所有的對象。這就是透明形式的合成模式。

這個選擇的缺點是不夠安全,因爲樹葉類對象和合成類對象在本質上是有區別的。樹葉類對象不可能有下一個層次的對象,因此add()、remove()以及getChild()方法沒有意義,是在編譯時期不會出錯,而只會在運行時期纔會出錯。

安全方式

第二種選擇是在Composite類裏面聲明所有的用來管理子類對象的方法。這樣的做法是安全的做法,因爲樹葉類型的對象根本就沒有管理子類對象的方法,因此,如果客戶端對樹葉類對象使用這些方法時,程序會在編譯時期出錯。

這個選擇的缺點是不夠透明,因爲樹葉類和合成類將具有不同的接口。

這兩個形式各有優缺點,需要根據軟件的具體情況做出取捨決定。


三、 安全式的合成模式的結構

安全式的合成模式要求管理聚集的方法只出現在樹枝構件類中,而不出現在樹葉構件中。

 Pic60.gif

這種形式涉及到三個角色:

  • 抽象構件(Component)角色:這是一個抽象角色,它給參加組合的對象定義出公共的接口及其默認行爲,可以用來管理所有的子對象。在安全式的合成模式裏,構件角色並不是定義出管理子對象的方法,這一定義由樹枝構件對象給出。
  • 樹葉構件(Leaf)角色:樹葉對象是沒有下級子對象的對象,定義出參加組合的原始對象的行爲。
  • 樹枝構件(Composite)角色:代表參加組合的有下級子對象的對象。樹枝對象給出所有的管理子對象的方法,如add()、remove()、getChild()等。


四、 安全式的合成模式實現

以下示例性代碼演示了安全式的合成模式代碼:

None.gif// Composite pattern -- Structural example  
None.gif
using System;
None.gif
using System.Text;
None.gif
using System.Collections;
None.gif
None.gif
// "Component"
None.gif
abstract class Component
ExpandedBlockStart.gif
{
InBlock.gif  
// Fields
InBlock.gif
  protected string name;
InBlock.gif
InBlock.gif  
// Constructors
InBlock.gif
  public Component( string name )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
this.name = name;
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
// Operation
InBlock.gif
  public abstract void Display( int depth );
ExpandedBlockEnd.gif}

None.gif
None.gif
// "Composite"
None.gif
class Composite : Component
ExpandedBlockStart.gif
{
InBlock.gif  
// Fields
InBlock.gif
  private ArrayList children = new ArrayList();
InBlock.gif
InBlock.gif  
// Constructors
ExpandedSubBlockStart.gif
  public Composite( string name ) : base( name ) {}
InBlock.gif
InBlock.gif  
// Methods
InBlock.gif
  public void Add( Component component )
ExpandedSubBlockStart.gif  
{
InBlock.gif    children.Add( component );
ExpandedSubBlockEnd.gif  }

InBlock.gif  
public void Remove( Component component )
ExpandedSubBlockStart.gif  
{
InBlock.gif    children.Remove( component );
ExpandedSubBlockEnd.gif  }

InBlock.gif  
public override void Display( int depth )
ExpandedSubBlockStart.gif  
{
InBlock.gif    Console.WriteLine( 
new String( '-', depth ) + name );
InBlock.gif
InBlock.gif    
// Display each of the node's children
InBlock.gif
    foreach( Component component in children )
InBlock.gif      component.Display( depth 
+ 2 );
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

None.gif
None.gif
// "Leaf"
None.gif
class Leaf : Component
ExpandedBlockStart.gif
{
InBlock.gif  
// Constructors
ExpandedSubBlockStart.gif
  public Leaf( string name ) : base( name ) {}
InBlock.gif
InBlock.gif  
// Methods
InBlock.gif
  public override void Display( int depth )
ExpandedSubBlockStart.gif  
{
InBlock.gif    Console.WriteLine( 
new String( '-', depth ) + name );
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

None.gif
ExpandedBlockStart.gif
/// <summary>
InBlock.gif
/// Client test
ExpandedBlockEnd.gif
/// </summary>

None.gifpublic class Client
ExpandedBlockStart.gif
{
InBlock.gif  
public static void Main( string[] args )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
// Create a tree structure
InBlock.gif
    Composite root = new Composite( "root" );
InBlock.gif    root.Add( 
new Leaf( "Leaf A" ));
InBlock.gif    root.Add( 
new Leaf( "Leaf B" ));
InBlock.gif    Composite comp 
= new Composite( "Composite X" );
InBlock.gif
InBlock.gif    comp.Add( 
new Leaf( "Leaf XA" ) );
InBlock.gif    comp.Add( 
new Leaf( "Leaf XB" ) );
InBlock.gif    root.Add( comp );
InBlock.gif
InBlock.gif    root.Add( 
new Leaf( "Leaf C" ));
InBlock.gif
InBlock.gif    
// Add and remove a leaf
InBlock.gif
    Leaf l = new Leaf( "Leaf D" );
InBlock.gif    root.Add( l );
InBlock.gif    root.Remove( l );
InBlock.gif
InBlock.gif    
// Recursively display nodes
InBlock.gif
    root.Display( 1 );
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}


五、 透明式的合成模式結構

與安全式的合成模式不同的是,透明式的合成模式要求所有的具體構件類,不論樹枝構件還是樹葉構件,均符合一個固定的接口。

 Pic61.gif

這種形式涉及到三個角色:

  • 抽象構件(Component)角色:這是一個抽象角色,它給參加組合的對象規定一個接口,規範共有的接口及默認行爲。
  • 樹葉構件(Leaf)角色:代表參加組合的樹葉對象,定義出參加組合的原始對象的行爲。樹葉類會給出add()、remove()以及getChild()之類的用來管理子類對對象的方法的平庸實現。
  • 樹枝構件(Composite)角色:代表參加組合的有子對象的對象,定義出這樣的對象的行爲。


六、 透明式的合成模式實現

以下示例性代碼演示了安全式的合成模式代碼:

None.gif// Composite pattern -- Structural example  
None.gif

None.gif
using System;
None.gif
using System.Text;
None.gif
using System.Collections;
None.gif
None.gif
// "Component"
None.gif
abstract class Component
ExpandedBlockStart.gif
{
InBlock.gif  
// Fields
InBlock.gif
  protected string name;
InBlock.gif
InBlock.gif  
// Constructors
InBlock.gif
  public Component( string name )
ExpandedSubBlockStart.gif  
this.name = name; }
InBlock.gif
InBlock.gif  
// Methods
InBlock.gif
  abstract public void Add(Component c);
InBlock.gif  
abstract public void Remove( Component c );
InBlock.gif  
abstract public void Display( int depth );
ExpandedBlockEnd.gif}

None.gif
None.gif
// "Composite"
None.gif
class Composite : Component
ExpandedBlockStart.gif
{
InBlock.gif  
// Fields
InBlock.gif
  private ArrayList children = new ArrayList();
InBlock.gif
InBlock.gif  
// Constructors
ExpandedSubBlockStart.gif
  public Composite( string name ) : base( name ) {}
InBlock.gif
InBlock.gif  
// Methods
InBlock.gif
  public override void Add( Component component )
ExpandedSubBlockStart.gif  
{ children.Add( component ); }
InBlock.gif  
InBlock.gif  
public override void Remove( Component component )
ExpandedSubBlockStart.gif  
{ children.Remove( component ); }
InBlock.gif  
InBlock.gif  
public override void Display( int depth )
ExpandedSubBlockStart.gif  

InBlock.gif    Console.WriteLine( 
new String( '-', depth ) + name );
InBlock.gif
InBlock.gif    
// Display each of the node's children
InBlock.gif
    foreach( Component component in children )
InBlock.gif      component.Display( depth 
+ 2 );
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

None.gif
None.gif
// "Leaf"
None.gif
class Leaf : Component
ExpandedBlockStart.gif
{
InBlock.gif  
// Constructors
ExpandedSubBlockStart.gif
  public Leaf( string name ) : base( name ) {}
InBlock.gif
InBlock.gif  
// Methods
InBlock.gif
  public override void Add( Component c )
ExpandedSubBlockStart.gif  
{ Console.WriteLine("Cannot add to a leaf"); }
InBlock.gif
InBlock.gif  
public override void Remove( Component c )
ExpandedSubBlockStart.gif  
{ Console.WriteLine("Cannot remove from a leaf"); }
InBlock.gif
InBlock.gif  
public override void Display( int depth )
ExpandedSubBlockStart.gif  
{ Console.WriteLine( new String( '-', depth ) + name ); }
ExpandedBlockEnd.gif}

None.gif
ExpandedBlockStart.gif
/// <summary>
InBlock.gif
/// Client test
ExpandedBlockEnd.gif
/// </summary>

None.gifpublic class Client
ExpandedBlockStart.gif
{
InBlock.gif  
public static void Main( string[] args )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
// Create a tree structure
InBlock.gif
    Composite root = new Composite( "root" );
InBlock.gif    root.Add( 
new Leaf( "Leaf A" ));
InBlock.gif    root.Add( 
new Leaf( "Leaf B" ));
InBlock.gif    Composite comp 
= new Composite( "Composite X" );
InBlock.gif
InBlock.gif    comp.Add( 
new Leaf( "Leaf XA" ) );
InBlock.gif    comp.Add( 
new Leaf( "Leaf XB" ) );
InBlock.gif    root.Add( comp );
InBlock.gif
InBlock.gif    root.Add( 
new Leaf( "Leaf C" ));
InBlock.gif
InBlock.gif    
// Add and remove a leaf
InBlock.gif
    Leaf l = new Leaf( "Leaf D" );
InBlock.gif    root.Add( l );
InBlock.gif    root.Remove( l );
InBlock.gif
InBlock.gif    
// Recursively display nodes
InBlock.gif
    root.Display( 1 );
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}


七、 使用合成模式時考慮的幾個問題

  1. 明顯的給出父對象的引用。在子對象裏面給出父對象的引用,可以很容易的遍歷所有父對象。有了這個引用,可以方便的應用責任鏈模式。
  2. 在通常的系統裏,可以使用享元模式實現構件的共享,但是由於合成模式的對象經常要有對父對象的引用,因此共享不容易實現。
  3. 有時候系統需要遍歷一個樹枝結構的子構件很多次,這時候可以考慮把遍歷子構件的結果暫時存儲在父構件裏面作爲緩存。
  4. 關於使用什麼數據類型來存儲子對象的問題,在示意性的代碼中使用了ArrayList,在實際系統中可以使用其它聚集或數組等。
  5. 客戶端儘量不要直接調用樹葉類中的方法,而是藉助其父類(Component)的多態性完成調用,這樣可以增加代碼的複用性。


八、 和尚的故事

Pic62.gif

Pic63.gif


九、 一個實際應用Composite模式的例子

下面是一個實際應用中的程序,演示了通過一些基本圖像元素(直線、園等)以及一些複合圖像元素(由基本圖像元素組合而成)構建複雜的圖形樹的過程。

None.gif// Composite pattern -- Real World example  
None.gif

None.gif
using System;
None.gif
using System.Collections;
None.gif
None.gif
// "Component"
None.gif
abstract class DrawingElement
ExpandedBlockStart.gif
{
InBlock.gif  
// Fields
InBlock.gif
  protected string name;
InBlock.gif
InBlock.gif  
// Constructors
InBlock.gif
  public DrawingElement( string name )
ExpandedSubBlockStart.gif  
this.name = name; }
InBlock.gif 
InBlock.gif  
// Operation
InBlock.gif
  abstract public void Display( int indent );
ExpandedBlockEnd.gif}

None.gif
None.gif
// "Leaf"
None.gif
class PrimitiveElement : DrawingElement
ExpandedBlockStart.gif
{
InBlock.gif  
// Constructors
ExpandedSubBlockStart.gif
  public PrimitiveElement( string name ) : base( name ) {}
InBlock.gif
InBlock.gif  
// Operation
InBlock.gif
  public override void Display( int indent )
ExpandedSubBlockStart.gif  
{
InBlock.gif    Console.WriteLine( 
new String( '-', indent ) + 
InBlock.gif      
" draw a {0}", name );
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

None.gif
None.gif
// "Composite"
None.gif
class CompositeElement : DrawingElement
ExpandedBlockStart.gif
{
InBlock.gif  
// Fields
InBlock.gif
  private ArrayList elements = new ArrayList();
InBlock.gif 
InBlock.gif  
// Constructors
ExpandedSubBlockStart.gif
  public CompositeElement( string name ) : base( name ) {}
InBlock.gif
InBlock.gif  
// Methods
InBlock.gif
  public void Add( DrawingElement d )
ExpandedSubBlockStart.gif  
{ elements.Add( d ); }
InBlock.gif
InBlock.gif  
public void Remove( DrawingElement d )
ExpandedSubBlockStart.gif  
{ elements.Remove( d ); }
InBlock.gif
InBlock.gif  
public override void Display( int indent )
ExpandedSubBlockStart.gif  
{
InBlock.gif    Console.WriteLine( 
new String( '-', indent ) +
InBlock.gif      
"" + name );
InBlock.gif
InBlock.gif    
// Display each child element on this node
InBlock.gif
    foreach( DrawingElement c in elements )
InBlock.gif      c.Display( indent 
+ 2 );
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

None.gif 
ExpandedBlockStart.gif
/// <summary>
InBlock.gif
///  CompositeApp test
ExpandedBlockEnd.gif
/// </summary>

None.gifpublic class CompositeApp
ExpandedBlockStart.gif
{
InBlock.gif  
public static void Main( string[] args )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
// Create a tree structure
InBlock.gif
    CompositeElement root = new  
InBlock.gif      CompositeElement( 
"Picture" );
InBlock.gif    root.Add( 
new PrimitiveElement( "Red Line" ));
InBlock.gif    root.Add( 
new PrimitiveElement( "Blue Circle" ));
InBlock.gif    root.Add( 
new PrimitiveElement( "Green Box" ));
InBlock.gif
InBlock.gif    CompositeElement comp 
= new  
InBlock.gif      CompositeElement( 
"Two Circles" );
InBlock.gif    comp.Add( 
new PrimitiveElement( "Black Circle" ) );
InBlock.gif    comp.Add( 
new PrimitiveElement( "White Circle" ) );
InBlock.gif    root.Add( comp );
InBlock.gif
InBlock.gif    
// Add and remove a PrimitiveElement
InBlock.gif
    PrimitiveElement l = new PrimitiveElement( "Yellow Line" );
InBlock.gif    root.Add( l );
InBlock.gif    root.Remove( l );
InBlock.gif
InBlock.gif    
// Recursively display nodes
InBlock.gif
    root.Display( 1 );
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

合成模式與很多其它模式都有聯繫,將在後續內容中逐步介紹。


參考文獻:
閻宏,《Java與模式》,電子工業出版社
[美]James W. Cooper,《C#設計模式》,電子工業出版社
[美]Alan Shalloway  James R. Trott,《Design Patterns Explained》,中國電力出版社
[美]Robert C. Martin,《敏捷軟件開發-原則、模式與實踐》,清華大學出版社
[美]Don Box, Chris Sells,《.NET本質論 第1卷:公共語言運行庫》,中國電力出版社

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章