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

来源:互联网 发布:手机上可以开淘宝店吗 编辑:程序博客网 时间:2024/04/30 01:42
 .
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);        }    }}

原创粉丝点击