2024-11-22 01:15:58 +00:00
|
|
|
import importlib
|
|
|
|
from abc import ABC, abstractmethod
|
|
|
|
|
|
|
|
# 抽象主题
|
|
|
|
class Subject(ABC):
|
|
|
|
@abstractmethod
|
|
|
|
def request(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
# 真实对象 1
|
|
|
|
class RealSubjectA(Subject):
|
|
|
|
def request(self):
|
|
|
|
print("RealSubjectA: Handling request.")
|
|
|
|
|
|
|
|
# 真实对象 2
|
|
|
|
class RealSubjectB(Subject):
|
|
|
|
def request(self):
|
|
|
|
print("RealSubjectB: Handling request.")
|
|
|
|
|
|
|
|
# 默认代理(备用对象)
|
|
|
|
class DefaultSubject(Subject):
|
|
|
|
def request(self):
|
|
|
|
print("DefaultSubject: Handling request as fallback.")
|
|
|
|
|
|
|
|
# 代理对象
|
|
|
|
class Proxy(Subject):
|
|
|
|
def __init__(self, real_class_name: str):
|
|
|
|
self._real_subject = self._create_real_subject(real_class_name)
|
|
|
|
|
|
|
|
def request(self):
|
|
|
|
print("Proxy: Additional logic before delegating.")
|
|
|
|
self._real_subject.request()
|
|
|
|
print("Proxy: Additional logic after delegating.")
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _create_real_subject(class_name: str) -> Subject:
|
|
|
|
# 动态加载类
|
|
|
|
try:
|
|
|
|
cls = globals().get(class_name) # 从当前全局作用域中获取类
|
|
|
|
if cls is None:
|
|
|
|
raise KeyError
|
|
|
|
if not issubclass(cls, Subject):
|
|
|
|
raise TypeError(f"{class_name} is not a subclass of Subject.")
|
|
|
|
return cls()
|
|
|
|
except (KeyError, TypeError):
|
|
|
|
print(f"Warning: Class '{class_name}' not found or invalid. Using DefaultSubject.")
|
|
|
|
return DefaultSubject()
|
|
|
|
|
|
|
|
# 客户端代码
|
|
|
|
def client_code(proxy: Proxy):
|
|
|
|
proxy.request()
|
|
|
|
|
|
|
|
# 使用代理,通过字符串指定真实类
|
|
|
|
print("Client: Using RealSubjectA:")
|
|
|
|
proxy_a = Proxy("RealSubjectA")
|
|
|
|
client_code(proxy_a)
|
|
|
|
|
|
|
|
print("\nClient: Using RealSubjectB:")
|
|
|
|
proxy_b = Proxy("RealSubjectB")
|
|
|
|
client_code(proxy_b)
|
|
|
|
|
|
|
|
print("\nClient: Attempting to use a non-existent class:")
|
|
|
|
proxy_invalid = Proxy("NonExistentClass")
|
|
|
|
client_code(proxy_invalid)
|