您的位置:首页 > 其它

设计模式学习8 Composite

2010-07-21 13:40 344 查看

应用场景:

客户代码过多的依赖对象容器的复杂的内部实现,对象容器内部的变化将导致客户端的代码的剧烈变化。将客户代码和对象容器解耦,从而更能够应对变化。



实现代码:

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

    public class SingleBox : IBox
    {
        public void Process()
        {
            // do process for myself
        }

        public void Add(IBox box)
        {
            // 两个实现方案
            // 1. do nothing
            // 2. throw exception
        }

        public void Remove(IBox box)
        {
            // 1. do nothing or
            // 2. throw exception
        }
    }

    public class ContainerBox : IBox
    {
        // do process for myself

        // do the process fo r the box in the list

        ArrayList list;
        public void Process()
        {
            if (list != null)
            {
                foreach (IBox box in list)
                {
                    box.Process();
                }
            }
        }

        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 ArrayList GetBoxes()
        {
            return list;
        }
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: