c#设计模式之组合模式

将对象组合成树形结构以表示“部分-整体”的层次结构,使客户端对单个对象和组合对象保持一致的方式处理

类图如下:


Component

 public abstract class Component
    {
        public abstract void Add(Component component);
        public abstract void Remove(Component component);
        public abstract List GetChild();
        public abstract void Display();
    }

Composit

public class Composit : Component
    {
        private List components = new List();
        public override void Add(Component component)
        {
            this.components.Add(component);
        }

        public override void Remove(Component component)
        {
            this.components.Remove(component);
        }
        public override void Display()
        {
            Console.WriteLine($"Composit{this.GetHashCode()}");
            foreach (var component in this.components)
            {
                component.Display();
            }
        }

        public override List GetChild()
        {
            return this.components;
        }

    }

LeafComposit

public class LeafComposit : Component
    {
        public override void Add(Component component)
        {
        }

        public override void Display()
        {
            Console.WriteLine($"Composit{this.GetHashCode()}");
        }

        public override List GetChild()
        {
            return null;
        }

        public override void Remove(Component component)
        {
        }
    }

调用

 static void Main(string[] args)
        {
            Component head = new Composit();
            Component leaf = new LeafComposit();

            head.Add(leaf);

            head.Display();
        }

优点:

  1. 清晰表示具有层次的树形对象
  2. 简化客户端调用
  3. 符合开闭原则,方便扩展component的子类

源代码地址: 点击我下载 提取码: khg7

你可能感兴趣的:(c#设计模式之组合模式)