設計模式之組合模式 組合模式 Composite

組合模式 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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章