組合模式通過將多個具有相同屬性和行為的物件組裝成一個類似樹形結構的單一物件。以此來表示各個物件之間的層次關係。
前言
組合模式屬於結構型模式,通過將多個相似物件組合到一起,從而能夠構建出一個樹形的 整體-部分 的關係。保證了單個物件和組合物件的使用方式是一致的。在現實場景中,類似電腦中資料夾的瀏覽展示,可以聯想到 組合模式。
類圖描述
略
程式碼實現
1、具體實現
public class Employee
{
private string name;
private string dept;
private int salary;
private List<Employee> subordinates;
public Employee(string name,string dept,int sal)
{
this.name = name;
this.dept = dept;
this.salary = sal;
subordinates = new List<Employee>();
}
public void Add(Employee e) => subordinates.Add(e);
public void Remove(Employee e) => subordinates.Remove(e);
public List<Employee> GetSubordinates() => this.subordinates;
public override string ToString() => $"Employee :[name:{name},dept:{dept},salary:{salary}]";
}
2、上層呼叫
class Program
{
static void Main(string[] args)
{
Employee CEO = new Employee("John", "CEO", 30000);
Employee headSales = new Employee("Robert", "Head Sales", 20000);
Employee headMarketing = new Employee("Michel", "Head Marketing", 20000);
Employee clerk1 = new Employee("Laura", "Marketing", 10000);
Employee clerk2 = new Employee("Bob", "Marketing", 10000);
Employee salesExecutive1 = new Employee("Richard", "Sales", 10000);
Employee salesExecutive2 = new Employee("Rob", "Sales", 10000);
CEO.Add(headSales);
CEO.Add(headMarketing);
headSales.Add(salesExecutive1);
headSales.Add(salesExecutive2);
headMarketing.Add(clerk1);
headMarketing.Add(clerk2);
Console.WriteLine(CEO);
foreach (var headEmployee in CEO.GetSubordinates())
{
Console.WriteLine(headEmployee);
foreach (var employee in headEmployee.GetSubordinates())
{
Console.WriteLine(employee);
}
}
Console.ReadKey();
}
}
總結
由於組合模式將各個具體具體實現都作為同一個實體類而不是依賴介面,所以違背了 依賴倒置 的原則。因此,在具體的使用場景中需要具體分析具體對待。