组合(Composite)模式 *

组合(Composite)模式:将对象组合树形结构以表示‘部分-整体’的层次结构。

 组合模式使得用户对单个对象和组合对象具有一致性 

/*
* 抽象构件(Component)角色:这是一个抽象角色,它给参与组合的对象规定一个接口。这个角色给出共有接口及其默认行为。
* 树叶构件(Leaf)角色:代表参加组合的树叶对象。一个树叶对象没有下级子对象。
* 树枝构件(Composite)角色:代表参加组合的有子对象的对象,并给出树枝构件对象的行为。
*/

 

基础代码:

     // 创建一个树结构
            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);
            Composite compss = new Composite("Composite Y");
            compss.Add(new Leaf("Leaf XXB"));
            comp.Add(compss);
            root.Add(new Leaf("Leaf C"));
            // 添加和删除叶子
            Leaf l = new Leaf("Leaf D");
            root.Add(l);
            root.Remove(l);

            // 递归地显示节点
            root.Display(1);

            Console.WriteLine("\n ============ \n");


    /// <summary>
    /// 抽象构件(Component)角色
    /// </summary>
    public abstract class Component
    {
        protected string name; 
        // 构造函数
        public Component(string name)
        {
            this.name = name;
        }
        // 操作
        public abstract void Display(int depth);
    }

    //  树枝构件(Composite)角色
    public class Composite : Component
    { 
        private ArrayList children = new ArrayList(); 
        //构造函数
        public Composite(string name) : base(name) { } 

        //方法
        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); 
            // 显示每个节点的孩子
            foreach (Component component in children)
                component.Display(depth + 3);
        }  
    }
    /// <summary>
    /// 树叶构件(Leaf)角色
    /// </summary>
    public class Leaf : Component
    {
        // 构造函数
        public Leaf(string name) : base(name) { } 
        // 从写函数
        public override void Display(int depth)
        {
            Console.WriteLine(new String('-', depth) + name);
        }
    }

 

posted @ 2014-06-16 14:45  dragon.net  阅读(202)  评论(0编辑  收藏  举报