一、 合成(Composite)模式
合成模式有時(shí)又叫做部分-整體模式(Part-Whole)。合成模式將對象組織到樹(shù)結構中,可以用來(lái)描述整體與部分的關(guān)系。合成模式可以使客戶(hù)端將單純元素與復合元素同等看待。
從和尚的故事談起
這是小時(shí)候我奶奶講的故事:從前有個(gè)山,山里有個(gè)廟,廟里有個(gè)老和尚在給小和尚講故事,講的什么故事呢?從前有個(gè)山,山里有個(gè)廟……。奶奶的故事要循環(huán)多少次,根據你多長(cháng)時(shí)間睡著(zhù)而定。在故事中有山、有廟、有和尚、有故事。因此,故事的角色有兩種:一種里面沒(méi)有其它角色;另一種內部有其它角色。
對象的樹(shù)結構
一個(gè)樹(shù)結構由兩種節點(diǎn)組成:樹(shù)枝節點(diǎn)和樹(shù)葉節點(diǎn)。樹(shù)枝節點(diǎn)可以有子節點(diǎn),而一個(gè)樹(shù)葉節點(diǎn)不可以有子節點(diǎn)。除了根節點(diǎn)外,其它節點(diǎn)有且只有一個(gè)父節點(diǎn)。
注意:一個(gè)樹(shù)枝節點(diǎn)可以不帶任何葉子,但是它因為有帶葉子的能力,因此仍然是樹(shù)枝節點(diǎn),而不會(huì )成為葉節點(diǎn)。一個(gè)樹(shù)葉節點(diǎn)永遠不可能帶有子節點(diǎn)。
二、 合成模式概述
下圖所示的類(lèi)圖省略了各個(gè)角色的細節。
可以看出,上面的類(lèi)圖結構涉及到三個(gè)角色:
- 抽象構件(Component)角色:這是一個(gè)抽象角色,它給參與組合的對象規定一個(gè)接口。這個(gè)角色給出共有接口及其默認行為。
- 樹(shù)葉構件(Leaf)角色:代表參加組合的樹(shù)葉對象。一個(gè)樹(shù)葉對象沒(méi)有下級子對象。
- 樹(shù)枝構件(Composite)角色:代表參加組合的有子對象的對象,并給出樹(shù)枝構件對象的行為。
可以看出,Composite類(lèi)型的對象可以包含其它Component類(lèi)型的對象。換而言之,Composite類(lèi)型對象可以含有其它的樹(shù)枝(Composite)類(lèi)型或樹(shù)葉(Leaf)類(lèi)型的對象。
合成模式的實(shí)現根據所實(shí)現接口的區別分為兩種形式,分別稱(chēng)為安全模式和透明模式。合成模式可以不提供父對象的管理方法,但合成模式必須在合適的地方提供子對象的管理方法(諸如:add、remove、getChild等)。
透明方式
作為第一種選擇,在Component里面聲明所有的用來(lái)管理子類(lèi)對象的方法,包括add()、remove(),以及getChild()方法。這樣做的好處是所有的構件類(lèi)都有相同的接口。在客戶(hù)端看來(lái),樹(shù)葉類(lèi)對象與合成類(lèi)對象的區別起碼在接口層次上消失了,客戶(hù)端可以同等同的對待所有的對象。這就是透明形式的合成模式。
這個(gè)選擇的缺點(diǎn)是不夠安全,因為樹(shù)葉類(lèi)對象和合成類(lèi)對象在本質(zhì)上是有區別的。樹(shù)葉類(lèi)對象不可能有下一個(gè)層次的對象,因此add()、remove()以及getChild()方法沒(méi)有意義,是在編譯時(shí)期不會(huì )出錯,而只會(huì )在運行時(shí)期才會(huì )出錯。
安全方式
第二種選擇是在Composite類(lèi)里面聲明所有的用來(lái)管理子類(lèi)對象的方法。這樣的做法是安全的做法,因為樹(shù)葉類(lèi)型的對象根本就沒(méi)有管理子類(lèi)對象的方法,因此,如果客戶(hù)端對樹(shù)葉類(lèi)對象使用這些方法時(shí),程序會(huì )在編譯時(shí)期出錯。
這個(gè)選擇的缺點(diǎn)是不夠透明,因為樹(shù)葉類(lèi)和合成類(lèi)將具有不同的接口。
這兩個(gè)形式各有優(yōu)缺點(diǎn),需要根據軟件的具體情況做出取舍決定。
三、 安全式的合成模式的結構
安全式的合成模式要求管理聚集的方法只出現在樹(shù)枝構件類(lèi)中,而不出現在樹(shù)葉構件中。
這種形式涉及到三個(gè)角色:
- 抽象構件(Component)角色:這是一個(gè)抽象角色,它給參加組合的對象定義出公共的接口及其默認行為,可以用來(lái)管理所有的子對象。在安全式的合成模式里,構件角色并不是定義出管理子對象的方法,這一定義由樹(shù)枝構件對象給出。
- 樹(shù)葉構件(Leaf)角色:樹(shù)葉對象是沒(méi)有下級子對象的對象,定義出參加組合的原始對象的行為。
- 樹(shù)枝構件(Composite)角色:代表參加組合的有下級子對象的對象。樹(shù)枝對象給出所有的管理子對象的方法,如add()、remove()、getChild()等。
四、 安全式的合成模式實(shí)現
以下示例性代碼演示了安全式的合成模式代碼:
// Composite pattern -- Structural example
using System;
using System.Text;
using System.Collections;
// "Component"
abstract class Component
{
// Fields
protected string name;
// Constructors
public Component( string name )
{
this.name = name;
}
// Operation
public abstract void Display( int depth );
}
// "Composite"
class Composite : Component
{
// Fields
private ArrayList children = new ArrayList();
// Constructors
public Composite( string name ) : base( name ) {}
// Methods
public void Add( Component component )
{
children.Add( component );
}
public void Remove( Component component )
{
children.Remove( component );
}
public override void Display( int depth )
{
Console.WriteLine( new String( ‘-‘, depth ) + name );
// Display each of the node‘s children
foreach( Component component in children )
component.Display( depth + 2 );
}
}
// "Leaf"
class Leaf : Component
{
// Constructors
public Leaf( string name ) : base( name ) {}
// Methods
public override void Display( int depth )
{
Console.WriteLine( new String( ‘-‘, depth ) + name );
}
}
/**////
/// Client test
/// public class Client
{
public static void Main( string[] args )
{
// Create a tree structure
Composite root = new Composite( "root" );
root.Add( new Leaf( "Leaf A" ));
root.Add( new Leaf( "Leaf B" ));
Composite comp = new Composite( "Composite X" );
comp.Add( new Leaf( "Leaf XA" ) );
comp.Add( new Leaf( "Leaf XB" ) );
root.Add( comp );
root.Add( new Leaf( "Leaf C" ));
// Add and remove a leaf
Leaf l = new Leaf( "Leaf D" );
root.Add( l );
root.Remove( l );
// Recursively display nodes
root.Display( 1 );
}
}
五、 透明式的合成模式結構
與安全式的合成模式不同的是,透明式的合成模式要求所有的具體構件類(lèi),不論樹(shù)枝構件還是樹(shù)葉構件,均符合一個(gè)固定的接口。
這種形式涉及到三個(gè)角色:
- 抽象構件(Component)角色:這是一個(gè)抽象角色,它給參加組合的對象規定一個(gè)接口,規范共有的接口及默認行為。
- 樹(shù)葉構件(Leaf)角色:代表參加組合的樹(shù)葉對象,定義出參加組合的原始對象的行為。樹(shù)葉類(lèi)會(huì )給出add()、remove()以及getChild()之類(lèi)的用來(lái)管理子類(lèi)對對象的方法的平庸實(shí)現。
- 樹(shù)枝構件(Composite)角色:代表參加組合的有子對象的對象,定義出這樣的對象的行為。
六、 透明式的合成模式實(shí)現
以下示例性代碼演示了安全式的合成模式代碼:
// Composite pattern -- Structural example
using System;
using System.Text;
using System.Collections;
// "Component"
abstract class Component
{
// Fields
protected string name;
// Constructors
public Component( string name )
{ this.name = name; }
// Methods
abstract public void Add(Component c);
abstract public void Remove( Component c );
abstract public void Display( int depth );
}
// "Composite"
class Composite : Component
{
// Fields
private ArrayList children = new ArrayList();
// Constructors
public Composite( string name ) : base( name ) {}
// Methods
public override void Add( Component component )
{ children.Add( component ); }
public override void Remove( Component component )
{ children.Remove( component ); }
public override void Display( int depth )
{
Console.WriteLine( new String( ‘-‘, depth ) + name );
// Display each of the node‘s children
foreach( Component component in children )
component.Display( depth + 2 );
}
}
// "Leaf"
class Leaf : Component
{
// Constructors
public Leaf( string name ) : base( name ) {}
// Methods
public override void Add( Component c )
{ Console.WriteLine("Cannot add to a leaf"); }
public override void Remove( Component c )
{ Console.WriteLine("Cannot remove from a leaf"); }
public override void Display( int depth )
{ Console.WriteLine( new String( ‘-‘, depth ) + name ); }
}
/**////
/// Client test
/// public class Client
{
public static void Main( string[] args )
{
// Create a tree structure
Composite root = new Composite( "root" );
root.Add( new Leaf( "Leaf A" ));
root.Add( new Leaf( "Leaf B" ));
Composite comp = new Composite( "Composite X" );
comp.Add( new Leaf( "Leaf XA" ) );
comp.Add( new Leaf( "Leaf XB" ) );
root.Add( comp );
root.Add( new Leaf( "Leaf C" ));
// Add and remove a leaf
Leaf l = new Leaf( "Leaf D" );
root.Add( l );
root.Remove( l );
// Recursively display nodes
root.Display( 1 );
}
}
七、 使用合成模式時(shí)考慮的幾個(gè)問(wèn)題
- 明顯的給出父對象的引用。在子對象里面給出父對象的引用,可以很容易的遍歷所有父對象。有了這個(gè)引用,可以方便的應用責任鏈模式。
- 在通常的系統里,可以使用享元模式實(shí)現構件的共享,但是由于合成模式的對象經(jīng)常要有對父對象的引用,因此共享不容易實(shí)現。
- 有時(shí)候系統需要遍歷一個(gè)樹(shù)枝結構的子構件很多次,這時(shí)候可以考慮把遍歷子構件的結果暫時(shí)存儲在父構件里面作為緩存。
- 關(guān)于使用什么數據類(lèi)型來(lái)存儲子對象的問(wèn)題,在示意性的代碼中使用了ArrayList,在實(shí)際系統中可以使用其它聚集或數組等。
- 客戶(hù)端盡量不要直接調用樹(shù)葉類(lèi)中的方法,而是借助其父類(lèi)(Component)的多態(tài)性完成調用,這樣可以增加代碼的復用性。
八、 和尚的故事
九、 一個(gè)實(shí)際應用Composite模式的例子
下面是一個(gè)實(shí)際應用中的程序,演示了通過(guò)一些基本圖像元素(直線(xiàn)、園等)以及一些復合圖像元素(由基本圖像元素組合而成)構建復雜的圖形樹(shù)的過(guò)程。
// Composite pattern -- Real World example
using System;
using System.Collections;
// "Component"
abstract class DrawingElement
{
// Fields
protected string name;
// Constructors
public DrawingElement( string name )
{ this.name = name; }
// Operation
abstract public void Display( int indent );
}
// "Leaf"
class PrimitiveElement : DrawingElement
{
// Constructors
public PrimitiveElement( string name ) : base( name ) {}
// Operation
public override void Display( int indent )
{
Console.WriteLine( new String( ‘-‘, indent ) +
" draw a {0}", name );
}
}
// "Composite"
class CompositeElement : DrawingElement
{
// Fields
private ArrayList elements = new ArrayList();
// Constructors
public CompositeElement( string name ) : base( name ) {}
// Methods
public void Add( DrawingElement d )
{ elements.Add( d ); }
public void Remove( DrawingElement d )
{ elements.Remove( d ); }
public override void Display( int indent )
{
Console.WriteLine( new String( ‘-‘, indent ) +
"+ " + name );
// Display each child element on this node
foreach( DrawingElement c in elements )
c.Display( indent + 2 );
}
}
/**////
/// CompositeApp test
/// public class CompositeApp
{
public static void Main( string[] args )
{
// Create a tree structure
CompositeElement root = new
CompositeElement( "Picture" );
root.Add( new PrimitiveElement( "Red Line" ));
root.Add( new PrimitiveElement( "Blue Circle" ));
root.Add( new PrimitiveElement( "Green Box" ));
CompositeElement comp = new
CompositeElement( "Two Circles" );
comp.Add( new PrimitiveElement( "Black Circle" ) );
comp.Add( new PrimitiveElement( "White Circle" ) );
root.Add( comp );
// Add and remove a PrimitiveElement
PrimitiveElement l = new PrimitiveElement( "Yellow Line" );
root.Add( l );
root.Remove( l );
// Recursively display nodes
root.Display( 1 );
}
}
合成模式與很多其它模式都有聯(lián)系,將在后續內容中逐步介紹。