[設計模式練習]組合模式
將學校的組織及業務利用組合模式設計
類別圖
物件檔定義
using System.Collections.Generic;
using System.Text;
namespace DesignModelTest.組合
{
/// <summary>
/// 抽象類別:學校
/// </summary>
abstract class School
{
protected string name;
public School(string name)
{
this.name = name;
}
public abstract void Add(School c);//增加
public abstract void Remove(School c);//移除
public abstract void Display(int depth);//顯示深度
public abstract void Services();//業務
}
/// <summary>
/// 節點:學校分校
/// </summary>
class ConcreteSchool : School
{
private List<School> children = new List<School>();//子節點
public ConcreteSchool(string name) : base(name) { }
public override void Add(School c)
{
children.Add(c);
}
public override void Remove(School c)
{
children.Remove(c);
}
public override void Display(int depth)
{
Console.WriteLine(new string('-', depth) + name);
foreach (School school in children)
{
school.Display(depth + 2);
}
}
public override void Services()
{
foreach (School school in children)
{
school.Services();
}
}
}
/// <summary>
/// 葉:工學院
/// </summary>
class Engineering : School
{
public Engineering(string name) : base(name) { }
public override void Add(School c)
{
}
public override void Remove(School c)
{
}
public override void Display(int depth)
{
Console.WriteLine(new string('-', depth) + name);
}
public override void Services()
{
Console.WriteLine("{0} : 工學院業務 ", this.name);
}
}
/// <summary>
/// 葉:文學院
/// </summary>
class Liberal : School
{
public Liberal(string name) : base(name) { }
public override void Add(School c)
{
}
public override void Remove(School c)
{
}
public override void Display(int depth)
{
Console.WriteLine(new string('-', depth) + name);
}
public override void Services()
{
Console.WriteLine("{0} : 文學院業務 ", this.name);
}
}
}
用戶端程式碼
//設定根
DesignModelTest.組合.School root = new DesignModelTest.組合.ConcreteSchool("學校總部");
//增加葉
root.Add(new DesignModelTest.組合.Engineering("學校總部工學院"));
//增加葉
root.Add(new DesignModelTest.組合.Liberal("學校總部文學院"));
DesignModelTest.組合.School comp = new DesignModelTest.組合.ConcreteSchool("學校分部一");
comp.Add(new DesignModelTest.組合.Engineering("學校分部一工學院"));
comp.Add(new DesignModelTest.組合.Liberal("學校分部一文學院"));
//將節點(包括子節點及葉)加入根
root.Add(comp);
Console.WriteLine("\n結構圖");
root.Display(1);
//從根目錄開始作業
Console.WriteLine("\n業務");
root.Services();
Console.Read();
#endregion
輸出結果