59 lines
1.5 KiB
Python
59 lines
1.5 KiB
Python
|
|
"""
|
||
|
|
单例模式工具模块 - 统一管理全局服务实例
|
||
|
|
"""
|
||
|
|
|
||
|
|
from typing import TypeVar, Type, Dict, Callable, Optional
|
||
|
|
|
||
|
|
T = TypeVar('T')
|
||
|
|
|
||
|
|
|
||
|
|
class SingletonRegistry:
|
||
|
|
"""单例注册表 - 统一管理所有服务实例"""
|
||
|
|
|
||
|
|
_instances: Dict[str, object] = {}
|
||
|
|
_factories: Dict[str, Callable[[], object]] = {}
|
||
|
|
|
||
|
|
@classmethod
|
||
|
|
def register(cls, name: str, factory: Callable[[], T]) -> None:
|
||
|
|
"""注册服务工厂函数"""
|
||
|
|
cls._factories[name] = factory
|
||
|
|
|
||
|
|
@classmethod
|
||
|
|
def get(cls, name: str, instance_type: Type[T]) -> T:
|
||
|
|
"""获取或创建服务实例"""
|
||
|
|
if name not in cls._instances:
|
||
|
|
if name not in cls._factories:
|
||
|
|
raise KeyError(f"未注册的服务: {name}")
|
||
|
|
cls._instances[name] = cls._factories[name]()
|
||
|
|
return cls._instances[name]
|
||
|
|
|
||
|
|
@classmethod
|
||
|
|
def reset(cls, name: Optional[str] = None) -> None:
|
||
|
|
"""重置服务实例(用于测试)"""
|
||
|
|
if name:
|
||
|
|
cls._instances.pop(name, None)
|
||
|
|
else:
|
||
|
|
cls._instances.clear()
|
||
|
|
|
||
|
|
|
||
|
|
def singleton_factory(factory: Callable[[], T]) -> Callable[[], T]:
|
||
|
|
"""
|
||
|
|
单例工厂装饰器
|
||
|
|
|
||
|
|
用法:
|
||
|
|
@singleton_factory
|
||
|
|
def get_service():
|
||
|
|
return Service()
|
||
|
|
|
||
|
|
service = get_service() # 始终返回同一实例
|
||
|
|
"""
|
||
|
|
instance: Optional[T] = None
|
||
|
|
|
||
|
|
def wrapper() -> T:
|
||
|
|
nonlocal instance
|
||
|
|
if instance is None:
|
||
|
|
instance = factory()
|
||
|
|
return instance
|
||
|
|
|
||
|
|
return wrapper
|