组合模式(Composite Pattern):组合多个对象形成树形结构以表示“整体-部分”的结构层次。组合模式对单个对象(即叶子对象)和组合对象(即容器对象)的使用具有一致性。
组合模式又可以称为“整体-部分”(Part-Whole)模式,属于对象的结构模式,它将对象组织到树结构中,可以用来描述整体与部分的关系。
结构:
角色:
Component:抽象角色,为组合中的对象声明接口,在适当情况下实现所有类共有接口的缺省行为。
Leaf:参加组合的叶节点对象,没有子节点,定义原子对象的行为。
Composite:代表有子部件的部件,定义其行为,实现与子部件有关的操作。
示例代码:
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 );
}
}
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 );
}
}
Composite模式的要点:
Composite模式采用树形结构来实现普遍存在的对象容器,从而将“一对多”的关系转化为“一对一”的关系,使得客户代码可以一致地处理对象和对象容器,无需关心处理的是单个的对象,还是组合的对象容器。
将“客户代码与复杂的对象容器结构”解耦是Composite模式的核心思想,解耦之后,客户代码将与纯粹的抽象接口——而非对象容器的复杂内部实现结构——发生依赖关系,从而更能“应对变化”。