首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 設計模式:合成模式完整指南(二)— 安全式合成模式結構與實作

     編輯:關於C語言

安全式合成模式特點

管理聚集的方法(Add/Remove/GetChild)**僅出現在合成構件類別中**,葉構件完全不包含這些方法。

結構圖

三大角色

角色說明
抽象構件定義公共介面與預設行為,**不含**管理子物件方法
葉構件無子物件,實作基本行為
合成構件有子物件,提供所有管理方法

完整代碼實作


using System;
using System.Text;
using System.Collections;

abstract class Component
{
    protected string name;
    public Component(string name) => this.name = name;
    public abstract void Display(int depth);
}

class Composite : Component
{
    private ArrayList children = new ArrayList();
    public Composite(string name) : base(name) { }

    public void Add(Component c) => children.Add(c);
    public void Remove(Component c) => children.Remove(c);

    public override void Display(int depth)
    {
        Console.WriteLine(new string('-', depth) + name);
        foreach (Component c in children) c.Display(depth + 2);
    }
}

class Leaf : Component
{
    public Leaf(string name) : base(name) { }
    public override void Display(int depth)
        => Console.WriteLine(new string('-', depth) + name);
}

public class Client
{
    public static void Main()
    {
        Composite root = new Composite("root");
        root.Add(new Leaf("Leaf A"));
        root.Add(new Leaf("Leaf B"));

        Composite comp = new Composite("Composite X");
        comp.Add(new Leaf("Leaf XA"));
        comp.Add(new Leaf("Leaf XB"));
        root.Add(comp);

        root.Add(new Leaf("Leaf C"));

        Leaf l = new Leaf("Leaf D");
        root.Add(l);
        root.Remove(l);

        root.Display(1);
    }
}

執行結果

- root
-- Leaf A
-- Leaf B
-- Composite X
---- Leaf XA
---- Leaf XB
-- Leaf C

安全式優勢

  • 編譯時安全:嘗試 leaf.Add(...) 直接編譯錯誤
  • 介面純淨:葉節點介面不被管理方法污染
  • 意圖明確:代碼清楚表達「只有合成節點可管理子物件」

現代 C# 改良建議


// 介面隔離實現編譯時安全 + 統一介面
public interface IComponent { void Display(int depth); }
public interface IComposite : IComponent 
{ 
    void Add(IComponent c); 
    void Remove(IComponent c); 
}

public class Leaf : IComponent { /* ... */ }
public class Composite : IComposite 
{ 
    private List children = new();
    public void Add(IComponent c) => children.Add(c);
    public void Remove(IComponent c) => children.Remove(c);
    public void Display(int depth) { /* ... */ }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved