Composite

部分和整体的关系,允许客户以统一的方式来访问对象;

1.Component

-提供统一管理Childen的接,Add/Remove

-统一的操作接口Operation

public abstract class Component

    {

        protected string _name;

        public Component(string name)

        {

            _name = name;

        }

        public abstract void Add(Component c);

        public abstract void Remove(Component c);

        public abstract void Display(int depth);

    }

 

2.Composite:实现Component的接口

-Add/Remove

-包含存储Childen的对象

public class Root : Component

    {

        private List<Component> _children = new List<Component>();

        public Root(string name)

            : base(name)

        {

 

        }

 

        public override void Add(Component c)

        {

            _children.Add(c);

        }

 

        public override void Remove(Component c)

        {

            _children.Remove(c);

        }

 

        public override void Display(int depth)

        {

            Console.WriteLine(new string('-', depth) + _name);

            foreach (var component1 in _children)

            {

                component1.Display(depth+2);

            }

        }

    }

3.Leaf:实现Component的接口

public class Leaf : Component

    {

        public Leaf(string name):base(name)

        {

 

        }

 

        public override void Add(Component c)

        {

            throw new NotImplementedException();

        }

 

        public override void Remove(Component c)

        {

            throw new NotImplementedException();

        }

 

        public override void Display(int depth)

        {

            Console.WriteLine(new string('-', depth) + _name);

        }

    }

 

4.Client通过统一的接口调用Component

public class Client2

    {

        void Call()

        {

            Component root = new Root("root");

            root.Add(new Leaf("leaf A"));

            root.Add(new Leaf("leaf B"));

 

           Component comp = new Root("Composite X");

           comp.Add(new Leaf("Leaf XA"));

           comp.Add(new Leaf("Leaf XB"));

 

             root.Add(comp);

            root.Add(new Leaf("Leaf C"));

 

            root.Display(1);

 

        }

    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值