九、一個實際應用Composite模式的例子
下面是一個實際應用中的程序,演示了通過一些基本圖像元素(直線、園等)以及一些復合圖像元素(由基本圖像元素組合而成)構建復雜的圖形樹的過程。
// 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 );
}
}
/**//// <summary>
/// CompositeApp test
/// </summary>
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 );
}
}
合成模式與很多其它模式都有聯系,將在後續內容中逐步介紹。