using System;
interface ICalculator {
int Calculate(int x, int y);
}
class AddCalculator : ICalculator {
public int Calculate(int x, int y) => x + y;
}
class SubCalculator : ICalculator {
public int Calculate(int x, int y) => x - y;
}
class Program {
static void Main() {
ICalculator calc1 = new AddCalculator();
ICalculator calc2 = new SubCalculator();
Console.WriteLine(calc1.Calculate(3, 2)); // 5
Console.WriteLine(calc2.Calculate(3, 2)); // 1
Console.ReadKey();
}
}
此為策略模式核心:介面定義契約,具體類別提供演算法變體,執行時動態切換。
using System;
interface ILogger { void Log(string msg); }
interface IAuditor { void Log(string msg); }
class Service : ILogger, IAuditor {
// 顯式實作:不加 public,只能透過介面參考呼叫
void ILogger.Log(string msg) => Console.WriteLine($"[LOG] {msg}");
void IAuditor.Log(string msg) => Console.WriteLine($"[AUDIT] {msg}");
// 隱式實作(公開方法)可共存
public void Log(string msg) => Console.WriteLine($"[DEFAULT] {msg}");
}
class Program {
static void Main() {
Service svc = new Service();
svc.Log("Hello"); // [DEFAULT] Hello
ILogger logger = svc;
logger.Log("Hello"); // [LOG] Hello
IAuditor auditor = svc;
auditor.Log("Hello"); // [AUDIT] Hello
Console.ReadKey();
}
}
| 維度 | 隱式實作 | 顯式實作 |
|---|---|---|
| 語法 | public void Method() | void IInterface.Method() |
| 存取層級 | public | 無修飾詞(隱含 private) |
| 呼叫方式 | 類別實例、介面參考皆可 | 僅透過介面參考 |
| 同名衝突 | 無法區分 | 完美解決 |
| 多型行為 | 標準虛擬調度 | 介面調度(非虛擬) |
// 介面隔離:客戶端只依賴需要的介面
interface IReadOnlyRepository { T GetById(int id); IEnumerable GetAll(); }
interface IWriteRepository { void Add(T entity); void Update(T entity); void Delete(int id); }
// 具象類別實作多個介面
class UserRepository : IReadOnlyRepository, IWriteRepository {
// 顯式實作區分讀寫介面
User IReadOnlyRepository.GetById(int id) => /* 查詢 */;
IEnumerable IReadOnlyRepository.GetAll() => /* 查詢 */;
void IWriteRepository.Add(User entity) => /* 新增 */;
// ...
}
// 高層模組依賴抽象
class UserService {
private readonly IReadOnlyRepository _readRepo;
private readonly IWriteRepository _writeRepo;
public UserService(IReadOnlyRepository r, IWriteRepository w) {
_readRepo = r; _writeRepo = w;
}
}