我個人的偏好會是轉變工廠和命令實現之間的依賴關係,這樣每個命令都會在工廠註冊。
實現示例:
文件命令/ __ 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