static void Main(string[] args) { //BuilderExample(); //FactoryExample(); //FactoryMethodExample(); //FactoryMethodExample2(); //ProtoTypeExample(); //SingletonExample(); //AdapterExample(); //BridgeExample();
CompositeExample();
//Console.WriteLine("Hello World!"); Console.ReadKey(); }
static void CompositeExample() { 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("Tow Circles"); comp.Add(new PrimitiveElement("black circle")); comp.Add(new PrimitiveElement("white circle")); root.Add(comp);
PrimitiveElement pe = new PrimitiveElement("Yellow Line"); root.Add(pe); root.Remove(pe);
root.Display(1); }
main.cs |
using System; using System.Collections.Generic; using System.Text;
namespace DesignPatterns.Structural_Patterns.Composite { public abstract class DrawingElement { public abstract void Add(DrawingElement d); public abstract void Remove(DrawingElement d); public abstract void Display(Int32 indent);
protected string Name { get; private set; }
public DrawingElement(string name) { Name = name; } } }
DrawingElement.cs |
using System; using System.Collections.Generic; using System.Text;
namespace DesignPatterns.Structural_Patterns.Composite { public class CompositeElement : DrawingElement { private List<DrawingElement> elements;
public CompositeElement(string name) :base(name) { elements = new List<DrawingElement>(); }
public override void Add(DrawingElement d) { elements.Add(d); }
public override void Display(int indent) { Console.WriteLine(new String('-', indent) + "+ " + Name);
foreach (DrawingElement d in elements) { d.Display(indent + 2); }
}
public override void Remove(DrawingElement d) { elements.Remove(d); } } }
CompositeElement.cs |
using System; using System.Collections.Generic; using System.Text;
namespace DesignPatterns.Structural_Patterns.Composite { public class PrimitiveElement : DrawingElement { public PrimitiveElement(string name) : base(name) {
}
public override void Add(DrawingElement d) { Console.WriteLine("Cannot add to a PrimitiveElement"); }
public override void Display(Int32 indent) { Console.WriteLine(new String('-', indent) + " " + Name); }
public override void Remove(DrawingElement d) { Console.WriteLine("Cannot remove from a PrimitiveElement"); } } }
PrimitiveElement.cs |
참고 사이트
'C# 디자인패턴' 카테고리의 다른 글
12# Facade패턴 Structural Patterns (0) | 2019.06.03 |
---|---|
11# Decorator패턴 Structural Patterns (0) | 2019.06.03 |
09# Bridge패턴 Structural Patterns (0) | 2019.05.29 |
08# Adapter 패턴 Structural Patterns (0) | 2019.05.29 |
07# Singleton 패턴(thread safe) Creational Patterns (0) | 2019.05.24 |