我个人的偏好会是转变工厂和命令实现之间的依赖关系,这样每个命令都会在工厂注册。
实现示例:
文件命令/ __ init__.py:
import pkgutil
import commands
_commands = {}
def command(commandCls):
_commands[commandCls.__name__] = commandCls
return commandCls
def CommandFactory(commandnode):
name = commandnode.attrib['name']
if name in _commands.keys():
return _commands[name](commandnode)
# Load all commands
for loader, module_name, is_pkg in pkgutil.walk_packages(commands.__path__):
if module_name!=__name__:
module = loader.find_module(module_name).load_module(module_name)
文件命令/ mycommand.py:
from commands import command
@command
class MyCommand(object):
def __init__(self, commandnode):
pass
小测试:
from commands import CommandFactory
# Stub node implementation
class Node(object):
def __init__(self, name):
self.attrib = { "name": name }
if __name__=='__main__':
cmd = CommandFactory(Node("MyCommand"))
assert cmd.__class__.__name__=="MyCommand", "New command is instance of MyCommand"
cmd = CommandFactory(Node("UnknownCommand"))
assert cmd is None, "Returns None for unknown command type"
来源
2013-02-23 14:33:34
TAS
也许你希望将标题更改为“通话功能”按名称“?也许你可以尝试谷歌呢? ;) – 2013-02-23 13:14:09
我可能有一个研究失败,但我可以充满信心地说,这不是因为缺乏尝试。感谢关键字提示虽然:) – mnate 2013-02-25 13:34:26