試着這麼做:
class BaseRequest:
name = None
class FooRequest(BaseRequest):
name = 'I-95'
def response(self):
return "foo"
class BarRequest(BaseRequest):
name = 'P-22'
def response(self):
return "bar"
class RequestManager:
def __init__(self):
self.requests = {
FooRequest.name: FooRequest,
BarRequest.name: BarRequest
}
def generate_request(self, name):
if name in self.requests:
return self.requests[name]()
def register_request(self, request_class):
assert issubclass(request_class, BaseRequest), \
'Request class not a subclass of BaseRequest'
assert hasattr('name', request_class) and isinstance(request_class.name, str), \
'Request name not correctly configured'
self.requests[request_class.name] = request_class
然後:
manager = RequestManager()
request = manager.generate_request('I-95')
if request is not None:
print(request.response()) # "foo"
而對於註冊新的要求:
class NewRequest(BaseRequest):
name = 'N-1'
def response(self):
return "new"
manager = RequestManager()
manager.register_request(NewRequest)
request = manager.generate_request('N-1')
if request is not None:
print(request.response()) # "new"
我個人認爲這是一個使用了一個Singleton-pattern做得更好RequestManager(未經測試!):
class RequestManager:
instance = None
class __RequestManager:
requests = {
FooRequest.name: FooRequest,
BarRequest.name: BarRequest
}
def generate_request(self, name):
if name in self.requests:
return self.requests[name]()
def register_request(self, request_class):
assert issubclass(request_class, BaseRequest), \
'Request class not a subclass of BaseRequest'
assert hasattr('name', request_class) and isinstance(request_class.name, str), \
'Request name not correctly configured'
self.requests[request_class.name] = request_class
def __new__(cls):
if not cls.instance:
cls.instance = cls.__RequestManager()
return cls.instance
@staticmethod
def getInstance():
return RequestManager()
這將創建一個靜態訪問RequestManager例如:
manager = RequestManager.getInstance()
# Rest same as before, register some requests, etc.
manager2 = RequestManager.getInstance() # This is actually the same manager ie. the same instance!
manager
和manager2
共享相同的請求字典,所以更新通過其中一個適用於(從技術上來說,以同樣的經理,因爲您檢索相同的實例兩次)
您對目前的解決方案有什麼不喜歡的? – rrauenza
對於初學者來說,我想用類似於請求類型的列表來實現類似於enum的東西。鍵值對字典可能以請求的名稱作爲鍵和指向其功能的指針作爲其值。 – Answoquest