组合模式(Composite)

1 概述
当遇到这样的问题:一个对象它即可以是操作对象,又可以作为本身对象的容器。客户端代码在操作时,需要知道某个对象是容器对象还是操作对象。这样客户端代码就与容器、操作对象耦合。我们需要这样一种模式,使得即可以支持对象可以是操作对象或容器,并且也支持客户代码不需要知道某个对象是某个具体类型。

2 GOF中的定义
2.1意图
将对象组合成树形结构以表示“部分-整体”的层次结构。Composite模式使得用户对单个对象和组合对象的使用具有一致性。
2.2 结构图

3松耦合的实现——客户代码不需要区分某个对象是树支还是树叶

View Code
    public abstract class Component
    {
        protected string name;

        public Component() { }

        public Component(string name) 
        {
            this.name = name;
        }

        protected IList _childs = new List<Component>();

        public abstract void Add(Component com);

        public abstract void Remove(Component com);

        public abstract void Display(int depth);
    }

    public class Leaf:Component
    {
        public Leaf(string name):base(name){}

        public override void Add(Component com)
        {
            
        }

        public override void Remove(Component com)
        {
            
        }

        public override void Display(int depth)
        {
            Console.WriteLine(new string('-', depth) + name);
        }
    }

    public class Componsite : Component
    {
        public Componsite(string name) : base(name) { }
        public override void Add(Component com)
        {
            _childs.Add(com);
        }

        public override void Remove(Component com)
        {
            _childs.Remove(com);
        }

        public override void Display(int depth)
        {
            Console.WriteLine(new string('-', depth) + name);
            foreach (Component com in _childs)
            {
                com.Display(depth + 1);
            }
        }
    }

4总结
这里主要讲的是对客户代码透明操作的一种组合模式,即不管它是容器(Composite)还是操作对象(Leaf),我们让它都具有Add,Remove等方法,只不过在Leaf中我们实现为空的方法(或抛出异常),最终的好处是客户代码对这个树有一个一致的操作界面。

原文地址:https://www.cnblogs.com/dataadapter/p/2669180.html