Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
把多个对象组成树状结构来表示局部与整体,这样用户可以一样的对待单个对象和对象的组合。
interface IGraphic {
void Print();
}
class CompositeGraphic : IGraphic {
private readonly IList<IGraphic> _childGraphics = new List<IGraphic>();
public void Print() {
foreach (var childGraphic in _childGraphics) {
childGraphic.Print();
}
}
public void Add(IGraphic graphic) {
this._childGraphics.Add(graphic);
}
public void Remove(IGraphic graphic) {
this._childGraphics.Remove(graphic);
}
}
class Ellipse : IGraphic {
public void Print() {
Console.WriteLine("Ellipse");
}
}
class Program {
static void Main(string[] args) {
var ellipse1 = new Ellipse();
var ellipse2 = new Ellipse();
var ellipse3 = new Ellipse();
var ellipse4 = new Ellipse();
var graphic = new CompositeGraphic();
var graphic1 = new CompositeGraphic();
var graphic2 = new CompositeGraphic();
graphic1.Add(ellipse1);
graphic1.Add(ellipse2);
graphic1.Add(ellipse3);
graphic2.Add(ellipse4);
graphic.Add(graphic1);
graphic.Add(graphic2);
graphic.Print();
Console.ReadKey();
}
}