【发布时间】:2011-11-22 11:22:46
【问题描述】:
我已经读到使用命令模式是完成执行/撤消功能的最流行的方法之一。事实上,我已经看到可以堆叠一堆动作并反转它们以达到给定状态。但是,我不太确定如何在 Python 中做到这一点,而且我阅读的大多数教程都涉足概念,但没有展示 Python 中的实际实现。
有谁知道 Python 中的执行/撤消功能是如何工作的?
作为参考,这是我的(幼稚且可能充满错误)代码:
# command
class DrawCommand:
def __init__(self, draw, point1, point2):
self.draw = draw
self.point1 = point1
self.point2 = point2
def execute_drawing(self):
self.draw.execute(self.point1, self.point2)
def execute_undrawing(self):
self.draw.unexecute(self.point1, self.point2)
# invoker
class InvokeDrawALine:
def command(self, command):
self.command = command
def click_to_draw(self):
self.command.execute_drawing()
def undo(self):
self.command.execute_undrawing()
# receiver
class DrawALine:
def execute(self, point1, point2):
print("Draw a line from {} to {}".format(point1, point2))
def unexecute(self, point1, point2):
print("Erase a line from {} to {}".format(point1, point2))
实例化如下:
invoke_draw = InvokeDrawALine()
draw_a_line = DrawALine()
draw_command = DrawCommand(draw_a_line, 1, 2)
invoke_draw.command(draw_command)
invoke_draw.click_to_draw()
invoke_draw.undo()
输出:
Draw a line from 1 to 2
Erase a line from 1 to 2
显然,此测试不允许堆叠多个操作来撤消。也许我完全错了,所以我会很感激一些帮助。
【问题讨论】:
标签: python design-patterns command