使用者管理是幾乎所有應用的核心子系統。本文從業務需求出發,分析單一模型/單表、多模型/多表、模組化抽象三種架構演進,探討擴充性與維護性的平衡。
所有屬性放入一個 User 類別,UserType 欄位區分類型。優點:模型單一、查詢簡單。缺點:大量 Null 欄位浪費空間、程式碼充滿 if (type == ...) 判斷、違反單一職責原則。
依類型拆分:PersonalUser、EnterpriseUser 對應獨立資料表。優點:結構清晰、無空值浪費。缺點:
核心洩露:程式碼越貼近具體業務,復用性越低。採用組合模式:
public class User {
public string Username { get; set; }
public string PasswordHash { get; set; }
public IProfile Profile { get; set; } // 個人/企業資料模組
public IAuthentication Auth { get; set; } // 認證方式模組
public IWallet Wallet { get; set; } // 金融資訊模組(可選)
public IRoles Roles { get; set; } // 權限模組
}
IAuthentication 新類別此架構支援從簡單部落格到複雜電商平台的平滑演進。