1、结构图
2、代码
/*****************************************************************************************
* 意图:将对系那个组合成属性结构以表示“部分-整体”的层次结构。Composite使得用户
* 对单个对象和组合对象的使用具有一致性。
*
* 适用性:
* 1、你想表示对象的部分-整体层次结构。
* 2、你希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。
*
* 协作:
* 用户使用Component类接口与组合结构中的对象进行交互。如果接收者是一个叶节点,
* 则直接处理请求。如果接收者是Composite,它通常将请求发送给它的子部件,在转发请求之前,
* 与/或之后可能执行一些辅助操作。
*
* 作者:董怀信
* 日期:2009-05-31
*
* ****************************************************************************************/
using System;
using System.Collections.Generic;
namespace DesignPattern.StructuralPattern
{
/// <summary>
/// 为组合中的对象声明接口。
/// 在适当的情况下,实现所有类共有接口的缺省行为。
/// 声明一个接口用于访问和管理Component的子组件。
/// (可选)在递归结构中定义一个接口,用于访问一个父部件,并在合适的情况下实现它。
/// </summary>
public abstract class Component
{
protected List<Component> m_children;
public Component()
{
m_children = new List<Component>();
}
public abstract void Operation();
public virtual int Add(Component child)
{
throw new Exception("Not Support!");
}
public virtual bool Remove(Component child)
{
throw new Exception("Not Support!");
}
public virtual Component GetChild(int index)
{
throw new Exception("Not Support!");
}
}
/// <summary>
/// 在组合中表示叶节点对象,叶节点没有子节点。
/// 在组合中定义图元对象的行为。
/// </summary>
public class Leaf:Component
{
public override void Operation()
{
Console.WriteLine("Leaf:Operation");
}
}
/// <summary>
/// 定义有子部件的那些部件的行为。
/// 存储子部件。
/// 在Component接口中实现与子部件有关的操作。
/// </summary>
public class Composite : Component
{
public override void Operation()
{
Console.WriteLine("Composite:Operation Start;");
foreach (Component item in m_children)
{
item.Operation();
}
Console.WriteLine("Composite:Operation End;");
}
public override int Add(Component child)
{
int index = m_children.Count;
m_children.Add(child);
return index;
}
public override bool Remove(Component child)
{
if (m_children.Contains(child))
{
return m_children.Remove(child);
}
return true;
}
public override Component GetChild(int index)
{
if (index < m_children.Count)
{
return m_children[index];
}
return null;
}
}
/// <summary>
/// 测试客户,通过Component接口操纵组合部件的对象。
/// </summary>
public class Client
{
public void Test()
{
Component composite1 = new Composite();
Component composite2 = new Composite();
Component leaf1 = new Leaf();
composite2.Add(leaf1);
composite1.Add(composite2);
composite1.Operation();
}
}
}