[英]Patterns - Event Dispatcher without else if?
我正在為Detours庫創建一個Python包裝器。 該工具之一是調度程序,用於將所有已掛接的API調用發送到各種處理程序。
現在,我的代碼如下所示:
if event == 'CreateWindowExW':
# do something
elif event == 'CreateProcessW':
# do something
elif ...
這感覺很難看。 是否有一種模式可以創建事件調度程序,而不必為每個Windows API函數創建一個elif
分支?
一種不錯的方法是定義一個類,該類的方法等於相關的API函數名稱,再加上一個調度方法,該方法將調度為正確的方法。 例如:
class ApiDispatcher(object):
def handle_CreateWindowExW(self):
# do whatever
def handle_CreateProcessW(self):
# do this one
def dispatch(self, event):
method = getattr(self, 'handle_%s' % event)
method()
那些if最終將不得不去某個地方。 為什么不這樣做:
handler = get_handler(event)
handler.process()
在get_handler
您將擁有get_handler
,每個get_handler
返回一個在process
方法中完成其工作的對象。
一種替代方法是映射到可調用對象,如下所示:
def react_to_create_window_exw():
# do something with event here
pass
handlers = {
"CreateWindowExW" : react_to_create_window_exw
}
並且您可以這樣使用它:
handler = handlers[event]
handler()
這樣,您就不會使用任何if / else條件。
您可以使用dispatch dict方法。
def handle_CreateWindowExW():
print "CreateWindowExW"
#do something
events = {
"CreateWindowExW": handle_CreateWindowExW
}
events[event]()
這樣,您可以添加事件,而不必添加其他if
語句。
通常,在這種情況下,如果您有要執行的預定義操作列表,請使用地圖,例如
def CreateWindowExW():
print 'CreateWindowExW'
def CreateProcessW():
print 'CreateProcessW'
action_map = {
'CreateWindowExW': CreateWindowExW,
'CreateProcessW': CreateProcessW
}
for action in ['CreateWindowExW', 'UnkownAction']:
try:
action_map[action]()
except KeyError:
print action, "Not Found"
輸出:
CreateWindowExW
UnkownAction Not Found
因此,使用地圖可以創建功能非常強大的調度程序
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.