设计模式 组合模式

通过叶子和枝干的组合,实现树结构,以便于完成功能模块的复用。

效果如下:

代码如下:

    public class CompositeRun
    {
        public static void RunItem()
        {            
            string name;
            Composite one, item;

            Composite root = new Composite("南极总公司");


            name = "大洋洲分公司";
            one = new Composite(name);

            item = new leaf(name + "后勤");
            one.Add(item);
            item = new leaf(name + "战斗部");
            one.Add(item);

            name = "南洋分部";
            Composite oneX = new Composite(name);

            item = new leaf(name + "后勤");
            oneX.Add(item);
            item = new leaf(name + "战斗部");
            oneX.Add(item);

            one.Add(oneX);

            root.Add(one);

            name = "月球分公司";
            one = new Composite(name);

            item = new leaf(name + "后勤");
            one.Add(item);
            item = new leaf(name + "战斗部");
            one.Add(item);

            root.Add(one);

            root.Display(0);
        }
    }
    interface IComposite
    {
        void Add(Composite a);
        void Remove(Composite a);
        void Display(int depth);
    }

    public class Composite : IComposite
    {
        protected string _name;
        protected List<Composite> childs;
        public Composite(string name)
        {
            _name = name;
            childs = new List<Composite>();
        }
        public virtual void Add(Composite a)
        {
            childs.Add(a);
        }
        public virtual void Remove(Composite a)
        {
            childs.Remove(a);
        }

        public virtual void Display(int depth)
        {
            Console.WriteLine(new string('-', depth*4) + _name + " Including:");
            foreach (var item in childs)
            {
                item.Display(depth + 1);
            }
        }
    }

    public class leaf : Composite
    {
        public leaf(string name)
            : base(name)
        { }

        public override void Add(Composite a)
        {
            throw new Exception("Composite can not Add");
        }
        public override void Remove(Composite a)
        {
            throw new Exception("Composite can not Remove");
        }
        public override void Display(int depth)
        {
            Console.WriteLine(new string('-', depth*4) + _name + " Run");
        }

    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值