首頁
編程語言
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 Add(Component c);
    public abstract void Remove(Component c);
    public abstract void Display(int depth);
}

class Composite : Component
{
    private ArrayList children = new ArrayList();
    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 (Component c in children) c.Display(depth + 2);
    }
}

class Leaf : Component
{
    public Leaf(string name) : base(name) { }

    public override void Add(Component c)
        => Console.WriteLine("Cannot add to a leaf");

    public override void Remove(Component c)
        => Console.WriteLine("Cannot remove from a leaf");

    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);
    }
}

透明式 vs 安全式對比

維度透明式安全式
介面一致性完全一致葉節點無管理方法
客戶端調用無需區分類型需型別檢查或捕獲異常
葉節點安全性運行時錯誤/忽略編譯時保證
適用場景客戶端不區分葉/合成需嚴格防止誤調用

選擇建議

  • 客戶端統一處理所有節點 → 透明式
  • 嚴禁對葉節點調用管理方法 → 安全式
  • 現代 C# 可用介面隔離:IComponent + IComposite : IComponent 實現編譯時安全與介面統一並存
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved