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

C# 適配器模式實作:以繪圖顏色轉換為例

     編輯:關於C語言

情境:介面不相容的兩方

  • Client 期望呼叫 SetColor(string name)(如 "red", "white")
  • Adaptee (ProfessionalDrawer) 僅提供 SetColor(int r, int g, int b) RGB 介面

結構圖

Target (SimpleDrawer)
    ▲
    │ implements
Adapter (AssistantDrawer) ──uses──► Adaptee (ProfessionalDrawer)

完整程式碼

// 目標介面:客戶端依賴的抽象
public abstract class SimpleDrawer {
    public virtual void SetColor(string name) { }
}

// 適配器:繼承目標,組合被適配者
public class AssistantDrawer : SimpleDrawer {
    private readonly ProfessionalDrawer _adaptee = new ProfessionalDrawer();

    public override void SetColor(string name) {
        switch (name.ToLower()) {
            case "white": _adaptee.SetColor(255, 255, 255); break;
            case "black": _adaptee.SetColor(0, 0, 0); break;
            default: Console.WriteLine("I haven't seen this color!"); break;
        }
    }
}

// 被適配者:既有 RGB 介面
public class ProfessionalDrawer {
    public void SetColor(int r, int g, int b) {
        Console.WriteLine($"set the color to RGB({r},{g},{b})");
    }
}

// 測試驅動
public class TestApp {
    public static void Main() {
        var drawer = new AssistantDrawer();
        drawer.SetColor("red");   // 未定義 → 提示
        drawer.SetColor("black"); // RGB(0,0,0)
        drawer.SetColor("white"); // RGB(255,255,255)
    }
}

關鍵點解析

  1. 單向依賴:AssistantDrawer 依賴 SimpleDrawer(穩定抽象)與 ProfessionalDrawer(具體實作),符合依賴倒置原則。
  2. 開放封閉:新增顏色映射只需修改 AssistantDrawer,不動 ProfessionalDrawer。
  3. 物件適配器:採組合而非繼承 ProfessionalDrawer,避免繼承耦合,支援多重適配。

現代 C# 寫法建議

  • 目標介面改用 interface IDrawer { void SetColor(string name); },AssistantDrawer : IDrawer。
  • 映射表改用 Dictionary<string, (int r, int g, int b)> 或 IReadOnlyDictionary,擴充性更佳。
  • 若 ProfessionalDrawer 為第三方庫無法修改,可寫成 static 擴展方法:public static void SetColor(this ProfessionalDrawer d, string name),用法更自然。

適用場景

  • 整合第三方庫/舊系統,介面不符合領域模型
  • 單元測試中 Mock 非虛擬方法/密封類別
  • 跨平台抽象層(如:統一 iOS/Android 支付 SDK 介面)

適配器模式核心在於「介面轉換」,以最小代價橋接兩個既有契約,是棕地專案重構的利器。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved