[英]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.