def
将一个请求封装成一个对象, 从而让你使用不同的请求把客户端参数化, 对请求排队或者记录请求日志, 可以提供命令的撤销和恢复功能。
usage
● 类间解耦
调用者角色与接收者角色之间没有任何依赖关系, 调用者实现功能时只需调用Command抽象类的execute方法就可以, 不需要了解到底是哪个接收者执行。
● 可扩展性
Command的子类可以非常容易地扩展, 而调用者Invoker和高层次的模块Client不产生严重的代码耦合。
● 命令模式结合其他模式会更优秀
命令模式可以结合责任链模式, 实现命令族解析任务; 结合模板方法模式, 则可以减少Command子类的膨胀问题。
code
class MoveFileCommand(object):
def __init__(self, src, dest):
self.src = src
self.dest = dest
def execute(self):
self.rename(self.src, self.dest)
def undo(self):
self.rename(self.dest, self.src)
def rename(self, src, dest):
print(u"renaming %s to %s" % (src, dest))
os.rename(src, dest)
def main():
command_stack = []
# commands are just pushed into the command stack
command_stack.append(MoveFileCommand('foo.txt', 'bar.txt'))
command_stack.append(MoveFileCommand('bar.txt', 'baz.txt'))
# verify that none of the target files exist
assert(not lexists("foo.txt"))
assert(not lexists("bar.txt"))
assert(not lexists("baz.txt"))
try:
with open("foo.txt", "w"): # Creating the file
pass
# they can be executed later on
for cmd in command_stack:
cmd.execute()
# and can also be undone at will
for cmd in reversed(command_stack):
cmd.undo()
finally:
os.unlink("foo.txt")
if __name__ == "__main__":
main()
### OUTPUT ###
# renaming foo.txt to bar.txt
# renaming bar.txt to baz.txt
# renaming baz.txt to bar.txt
# renaming bar.txt to foo.txt