組合模式 Composite
Intro
組合模式,將物件組合成樹形結構以表示 “部分-整體” 的層次結構,組合模式使得用戶對單個物件和組合物件的使用具有一致性,
意圖:將物件組合成樹形結構以表示"部分-整體"的層次結構,組合模式使得用戶對單個物件和組合物件的使用具有一致性,
主要解決:它在我們樹型結構的問題中,模糊了簡單元素和復雜元素的概念,客戶程式可以像處理簡單元素一樣來處理復雜元素,從而使得客戶程式與復雜元素的內部結構解耦,
何時使用:
1、您想表示物件的部分-整體層次結構(樹形結構),
2、您希望用戶忽略組合物件與單個物件的不同,用戶將統一地使用組合結構中的所有物件,
如何解決:樹枝和葉子實作統一介面,樹枝內部組合該介面,
關鍵代碼:樹枝內部組合該介面,并且含有內部屬性 List,里面放 Component,
使用場景
當你發現需求中是體現部分與整體層次的結構時,以及你希望用戶可以忽略組合物件與單個物件的不同,統一地使用組合結構中的所有物件時,就應該考慮用組合模式了,
典型的使用場景:部分、整體場景,如樹形選單,檔案、檔案夾的管理,
Sample
public abstract class Component
{
protected string Name;
protected Component(string name)
{
Name = name;
}
public abstract void Add(Component c);
public abstract void Remove(Component c);
public abstract void Display(int depth);
}
public class Leaf : Component
{
public Leaf(string name) : base(name)
{
}
public override void Add(Component c)
{
throw new System.NotImplementedException();
}
public override void Remove(Component c)
{
throw new System.NotImplementedException();
}
public override void Display(int depth)
{
Console.WriteLine($"{new string('-', depth)} {Name}");
}
}
public class Composite : Component
{
private readonly List<Component> _children = new List<Component>();
public Composite(string name) : base(name)
{
}
public override void Add(Component c)
{
_children.Add(c);
}
public override void Remove(Component c)
{
_children.Remove(c);
}
public override void Display(int depth)
{
Console.WriteLine($"{new string('-', depth)} {Name}");
foreach (var component in _children)
{
component.Display(depth + 2);
}
}
}
var root = new Composite("root");
root.Add(new Leaf("Leaf A"));
root.Add(new Leaf("Leaf B"));
var co = new Composite("CompositeA");
co.Add(new Leaf("Leaf X"));
co.Add(new Leaf("Leaf Y"));
var co1 = new Composite("CompositeA");
co1.Add(new Leaf("Leaf P"));
co1.Add(new Leaf("Leaf Q"));
co.Add(co1);
root.Add(co);
root.Display(0);
Reference
- https://github.com/WeihanLi/DesignPatterns/tree/master/StructurePattern/CompositePattern
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/1628.html
標籤:C#
