結構性示範代碼
using System;
// 抽象化角色
class Abstraction
{
protected Implementor implementor;
public Implementor Implementor
{
set => implementor = value;
}
public virtual void Operation() => implementor.Operation();
}
// 實現化介面
abstract class Implementor
{
public abstract void Operation();
}
// 修正抽象化
class RefinedAbstraction : Abstraction
{
public override void Operation() => implementor.Operation();
}
// 具體實現化 A
class ConcreteImplementorA : Implementor
{
public override void Operation() => Console.WriteLine("ConcreteImplementorA Operation");
}
// 具體實現化 B
class ConcreteImplementorB : Implementor
{
public override void Operation() => Console.WriteLine("ConcreteImplementorB Operation");
}
// 客戶端測試:運行時熱切換實現
public class Client
{
public static void Main()
{
Abstraction abstraction = new RefinedAbstraction();
// 使用實現 A
abstraction.Implementor = new ConcreteImplementorA();
abstraction.Operation();
// 運行時切換至實現 B
abstraction.Implementor = new ConcreteImplementorB();
abstraction.Operation();
}
}
執行結果
ConcreteImplementorA Operation
ConcreteImplementorB Operation
關鍵機制解析
Abstraction 持有 Implementor 引用(組合而非繼承)
- 屬性注入實現**運行時熱切換**
RefinedAbstraction 可擴展抽象化行為而不修改實現化
- 客戶端僅依賴
Abstraction,不知具體 Implementor
橋接模式 vs 策略模式 對比