# Python 空对象模式 (Null Object)# NullObject 取代 None消除大量 if x is not None 判空检查# 使代码更简洁安全。示例NullLogger, NullDatabase, NullFileHandler。from abc import ABC, abstractmethodfrom typing import Optional# 抽象接口class Logger(ABC):abstractmethoddef info(self, msg: str) - None: ...abstractmethoddef error(self, msg: str) - None: ...class Database(ABC):abstractmethoddef connect(self) - None: ...abstractmethoddef query(self, sql: str) - list[dict]: ...abstractmethoddef close(self) - None: ...class FileHandler(ABC):abstractmethoddef read(self) - str: ...abstractmethoddef write(self, content: str) - None: ...# 真实实现class ConsoleLogger(Logger):def info(self, msg: str) - None:print(f[INFO] {msg})def error(self, msg: str) - None:print(f[ERROR] {msg})class SQLiteDatabase(Database):def connect(self) - None:print([DB] 连接数据库)def query(self, sql: str) - list[dict]:print(f[DB] 查询: {sql}); return []def close(self) - None:print([DB] 关闭连接)class RealFileHandler(FileHandler):def __init__(self, path: str):self._path pathdef read(self) - str:try:with open(self._path) as f:return f.read()except FileNotFoundError:return def write(self, content: str) - None:with open(self._path, w) as f:f.write(content)# 空对象实现class NullLogger(Logger):def info(self, msg: str) - None: passdef error(self, msg: str) - None: passclass NullDatabase(Database):def connect(self) - None: passdef query(self, sql: str) - list[dict]: return []def close(self) - None: passclass NullFileHandler(FileHandler):def read(self) - str: return def write(self, content: str) - None: pass# 应用层空对象替代 None 默认值class Application:def __init__(self, logger: Optional[Logger] None,db: Optional[Database] None,fh: Optional[FileHandler] None):self._log logger if logger else NullLogger()self._db db if db else NullDatabase()self._file fh if fh else NullFileHandler()def run(self) - None:self._log.info(启动应用); self._db.connect()results self._db.query(SELECT 1)data self._file.read()self._log.info(f结果: {len(results)} 条, 文件: {len(data)} 字符)self._db.close(); self._log.info(应用结束)if __name__ __main__:Application(loggerConsoleLogger()).run()Application().run() # 全空对象运行
Python空对象模式
发布时间:2026/5/30 13:43:58
# Python 空对象模式 (Null Object)# NullObject 取代 None消除大量 if x is not None 判空检查# 使代码更简洁安全。示例NullLogger, NullDatabase, NullFileHandler。from abc import ABC, abstractmethodfrom typing import Optional# 抽象接口class Logger(ABC):abstractmethoddef info(self, msg: str) - None: ...abstractmethoddef error(self, msg: str) - None: ...class Database(ABC):abstractmethoddef connect(self) - None: ...abstractmethoddef query(self, sql: str) - list[dict]: ...abstractmethoddef close(self) - None: ...class FileHandler(ABC):abstractmethoddef read(self) - str: ...abstractmethoddef write(self, content: str) - None: ...# 真实实现class ConsoleLogger(Logger):def info(self, msg: str) - None:print(f[INFO] {msg})def error(self, msg: str) - None:print(f[ERROR] {msg})class SQLiteDatabase(Database):def connect(self) - None:print([DB] 连接数据库)def query(self, sql: str) - list[dict]:print(f[DB] 查询: {sql}); return []def close(self) - None:print([DB] 关闭连接)class RealFileHandler(FileHandler):def __init__(self, path: str):self._path pathdef read(self) - str:try:with open(self._path) as f:return f.read()except FileNotFoundError:return def write(self, content: str) - None:with open(self._path, w) as f:f.write(content)# 空对象实现class NullLogger(Logger):def info(self, msg: str) - None: passdef error(self, msg: str) - None: passclass NullDatabase(Database):def connect(self) - None: passdef query(self, sql: str) - list[dict]: return []def close(self) - None: passclass NullFileHandler(FileHandler):def read(self) - str: return def write(self, content: str) - None: pass# 应用层空对象替代 None 默认值class Application:def __init__(self, logger: Optional[Logger] None,db: Optional[Database] None,fh: Optional[FileHandler] None):self._log logger if logger else NullLogger()self._db db if db else NullDatabase()self._file fh if fh else NullFileHandler()def run(self) - None:self._log.info(启动应用); self._db.connect()results self._db.query(SELECT 1)data self._file.read()self._log.info(f结果: {len(results)} 条, 文件: {len(data)} 字符)self._db.close(); self._log.info(应用结束)if __name__ __main__:Application(loggerConsoleLogger()).run()Application().run() # 全空对象运行