【设计模式】之 Composite 合成模式

 .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace DesignFactory
{
    /// <summary>
    /// 合成模式
    /// 基本图像元素 直线 圆
    /// 复合图像 图形树
    /// </summary>
    class CompositePattern
    {
    }

    abstract class DrawingElement
    {
        protected string name;
        public DrawingElement(string name)
        { this.name = name; }
        abstract public void Display(int indent);
    }

    class PrimitiveElement : DrawingElement
    {
        public PrimitiveElement(string name) : base(name) { }

        public override void Display(int indent)
        {
            Console.WriteLine(new String('-',indent) + "draw a {0}",name);
        }
    }

    class CompositeElement : DrawingElement
    {
        private ArrayList elements = new ArrayList();
        public CompositeElement(string name) : base(name) { }

        public void Add(DrawingElement d)
        { elements.Add(d); }

        public void Remove(DrawingElement d)
        { elements.Remove(d); }

        public override void Display(int indent)
        {
            Console.WriteLine(new String('-', indent) + "+", name);
            foreach (DrawingElement c in elements)
            {
                c.Display(indent + 2);
                
            }
        }
    }


    public class CompositeApp
    {
        public static void Main(string[] args)
        {
            CompositeElement root = new CompositeElement("Picture");
            root.Add(new PrimitiveElement("Red Line"));
            root.Add(new PrimitiveElement("Blue Circle"));
            root.Add(new PrimitiveElement("Green Box"));


            CompositeElement comp = new CompositeElement("Two Circles");
            comp.Add(new PrimitiveElement("Black Circle"));
            comp.Add(new PrimitiveElement("White Circle"));
            root.Add(comp);



            PrimitiveElement P = new PrimitiveElement("Yellow Line");
            root.Add(P);
            root.Remove(P);


            root.Display(1);
        }
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值