组合模式
using System.Collections;
using System.Collections.Generic;
public abstract class Graphics
{
public abstract void Draw();
}
public class Picture:Graphics
{
protected ArrayList list=new ArrayList();
public override void Draw()
{
foreach(Graphics g in list)
{
g.Draw();
}
}
public void Add(Graphics g)
{
list.Add(g);
}
public void Remove(Graphics g)
{
list.Remove(g);
}
}
public class Line:Graphics
{
public override void Draw()
{
Console.WriteLine("Line Draw();");
}
}
public class Circle:Graphics
{
public override void Draw()
{
Console.WriteLine("Circle Draw();");
}
}
public class Rectangle:Graphics
{
public override void Draw()
{
Console.WriteLine("Rectangle Draw();");
}
}
public class MyClass
{
public static void Main()
{
Picture myPicture=new Picture();
myPicture.Add(new Line());
myPicture.Add(new Circle());
Rectangle myRec=new Rectangle();
myPicture.Add(myRec);
myPicture.Draw();
Console.ReadLine();
}
}
using System;
using System.Collections;
using System.Collections.Generic;
public abstract class Component
{
protected string name;
public Component(string name)
{
this.name=name;
}
public abstract void Display(int depth);
}
public class Composite:Component
{
private ArrayList children=new ArrayList();
public Composite(string name):base(name)
{}
public void Add(Component component)
{
children.Add(component);
}
public void Remove(Component component)
{
children.Remove(component);
}
public override void Display(int depth)
{
Console.WriteLine(new String('-',depth)+this.name);
}
}
public class Leaf:Component
{
public Leaf(string name):base(name)
{
}
public override void Display(int depth)
{
Console.WriteLine(new String('-',depth)+this.name);
}
}
public class MyClass
{
public static void Main()
{
Composite root=new Composite("root");
root.Add(new Leaf("Leaf A"));
root.Add(new Leaf("Leaf B"));
Composite comp=new Composite("Composite X");
comp.Add(new Leaf("Leaf XA"));
comp.Add(new Leaf("Leaf XB"));
root.Add(comp);
root.Add(new Leaf("Leaf C"));
root.Add(new Leaf("Leaf D"));
Leaf l=new Leaf("Leaf E");
root.Add(l);
root.Remove(l);
root.Display(2);
Console.ReadLine();
}
}