某个子类型拥有list<父类型>,遍历信息时,直接调用父类型的抽象函数即可
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 组合模式
{
public abstract class Graphics
{
public abstract void Draw();
}
public class Line : Graphics
{
public override void Draw()
{
Console.WriteLine("Draw a Line");
}
}
public class Circle : Graphics
{
public override void Draw()
{
Console.WriteLine("Draw a Circle");
}
}
public class Rectangle : Graphics
{
public override void Draw()
{
Console.WriteLine("Draw a Rectangle");
}
}
public class Picture : Graphics
{
protected ArrayList picList = new ArrayList();
public override void Draw()
{
for (int i = 0; i < picList.Count; i++)
{
((Graphics)picList[i]).Draw();
}
}
public void Add(Graphics x)
{
picList.Add(x);
}
}
class Program
{
static void Main(string[] args)
{
Picture root = new Picture();
Picture branch1 = new Picture();
Picture branch2 = new Picture();
Line line1 = new Line();
Circle circle1 = new Circle();
Rectangle rect1 = new Rectangle();
Line line2 = new Line();
Circle circle2 = new Circle();
Rectangle rect2 = new Rectangle();
root.Add(line1);
root.Add(circle1);
root.Add(branch1);
branch1.Add(line2);
branch1.Add(branch2);
branch2.Add(circle2);
branch2.Add(rect2);
root.Add(rect1);
root.Draw();
Console.Read();
}
}
}
结果:
Draw a Line
Draw a Circle
Draw a Line
Draw a Circle
Draw a Rectangle
Draw a Rectangle
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 组合模式
{
public abstract class Graphics
{
public abstract void Draw();
}
public class Line : Graphics
{
public override void Draw()
{
Console.WriteLine("Draw a Line");
}
}
public class Circle : Graphics
{
public override void Draw()
{
Console.WriteLine("Draw a Circle");
}
}
public class Rectangle : Graphics
{
public override void Draw()
{
Console.WriteLine("Draw a Rectangle");
}
}
public class Picture : Graphics
{
protected List<Graphics> picList = new List<Graphics>();
public override void Draw()
{
for (int i = 0; i < picList.Count; i++)
{
picList[i].Draw();
}
}
public void Add(Graphics x)
{
picList.Add(x);
}
}
class Program
{
static void Main(string[] args)
{
Picture root = new Picture();
Picture branch1 = new Picture();
Picture branch2 = new Picture();
Line line1 = new Line();
Circle circle1 = new Circle();
Rectangle rect1 = new Rectangle();
Line line2 = new Line();
Circle circle2 = new Circle();
Rectangle rect2 = new Rectangle();
root.Add(line1);
root.Add(circle1);
root.Add(branch1);
branch1.Add(line2);
branch1.Add(branch2);
branch2.Add(circle2);
branch2.Add(rect2);
root.Add(rect1);
root.Draw();
Console.Read();
}
}
}