08.组合模式

namespace _09_Composite
{
    public interface IBox
    {
        void process();
    }

    public class SingleBox : IBox
    {
        public void process()
        {

        }
    }

    public class ContainerBox : IBox
    {
        public void process()
        {

        }
        public ArrayList getBoxes()
        {
            return new ArrayList();
        }
    }

    /// <summary>
    /// 客户代码
    /// </summary>
    internal class Program
    {
        //static void Main(string[] args)
        //{
        //    IBox box = new SingleBox();
        //    //客户代码与对象内部结构发生了耦合
        //    if (box is ContainerBox)
        //    {
        //        box.process();
        //        ArrayList list = ((ContainerBox)box).getBoxes();
        //    }
        //    else if (box is SingleBox)
        //    {
        //        box.process();
        //    }
        //}
    }
}

namespace _09_Composite_2
{
    public interface IBox
    {
        void Process();
        void Add(IBox box);
        void Remove(IBox box);
    }

    public class SingleBox : IBox
    {
        public void Add(IBox box)
        {
        }

        public void Remove(IBox box)
        {
        }

        public void Process()
        {
        }
    }

    public class ContainerBox : IBox
    {
        ArrayList list = null;

        public void Add(IBox box)
        {
            if (list == null)
            {
                list = new ArrayList();
            }
            list.Add(box);
        }

        public void Remove(IBox box)
        {
            if (list == null)
            {
                throw new Exception();
            }
            list.Remove(box);
        }

        public void Process()
        {
            //1.Do process for myself
            //2.Do process for the box in the list
            if (list != null)
            {
                foreach (IBox box in list)
                {
                    box.Process();
                }
            }
        }

        public IList getBoxes()
        {
            return list;
        }
    }

    /// <summary>
    /// 客户代码
    /// </summary>
    internal class Program
    {
        static void Main(string[] args)
        {
            IBox box = null;
            box = new SingleBox();
            box = new ContainerBox();
            //客户代码与抽象接口发生了耦合
            box.Process();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值