面向對象編程(OOP)本質可歸納為兩點:
① 封裝共性:將共同屬性與行為抽象為類
② 接口與實現分離:依賴抽象而非具體
一句話總結:「用一個類去實例化各種各樣的對象」。
if (osName.equals("SunOS") || osName.equals("Linux")) ...
else if (osName.equals("Windows NT") || osName.equals("Windows 95")) ...
問題:邏輯耦合、擴展需修改核心代碼、違反開閉原則。
private static String unixBox() { return "..."; }
private static String getTheString(String osName) { ... switch邏輯 ... }
改進:邏輯模塊化,但仍是集中式條件分發,新增 OS 仍需修改分發函數。
interface BoxSpecifier { String getStatement(); }
class UNIXBox implements BoxSpecifier { ... }
class WindowsBox implements BoxSpecifier { ... }
class OSDiscriminator { // 工廠
static BoxSpecifier getBoxSpecifier() { ... if-else 創建具體類 ... }
}
缺陷:工廠類仍包含所有具體類知識,新增類需修改工廠,類爆炸(每個 OS 一個文件),違反依賴倒置。
class OSDiscriminator {
static Map storage = new HashMap<>();
static BoxSpecifier getBoxSpecifier() {
BoxSpecifier v = storage.get(System.getProperty("os.name"));
return v != null ? v : DefaultBox.value;
}
static void register(String key, BoxSpecifier v) { storage.put(key, v); }
static { WindowsBox.register(); UNIXBox.register(); MacBox.register(); }
}
class UNIXBox implements BoxSpecifier {
static final UNIXBox value = new UNIXBox(); // 單例
static void register() {
OSDiscriminator.register("SunOS", value);
OSDiscriminator.register("Linux", value);
}
}
亮點:
「越來越難看懂」是過度設計的信號。
OOP 服務於變化管理,而非炫技。
原則:簡單場景用 if-else/switch;預期頻繁擴展、多維度變化時,再引入多態+註冊表。
合理使用 > 濫用模式。
文章來源:酷殼《如何理解面向對象編程》