客戶端不應依賴它不需要的介面;一個類對另一個類的依賴應建立在最小介面上。
「胖介面」包含過多方法,導致實現類被迫實現不需要的方法(拋出異常或空實現),違反單一職責,增加耦合與維護成本。
interface IWorker {
void work();
void eat(); // 機器人不需要
}
class Worker implements IWorker {
public void work() { System.out.println("工作中..."); }
public void eat() { System.out.println("吃飯..."); }
}
class Robot implements IWorker {
public void work() { System.out.println("精準作業..."); }
public void eat() { throw new UnsupportedOperationException("機器人不吃飯"); } // 差劣設計
}
interface IWorkable { void work(); }
interface IEatable { void eat(); }
class Worker implements IWorkable, IEatable { /* 同時實現 */ }
class Robot implements IWorkable { /* 僅實現需要的 */ }
| 優點 | 缺點/風險 |
|---|---|
| 降低耦合,實現類僅依賴所需 | 介面過度細碎導致「介面爆炸」,維護成本上升 |
| 提高內聚,每個介面職責單一 | 客戶端可能需依賴多個介面,使用稍繁瑣 |
| 支援多重實現組合,靈活復用 |