在Python中使用命令模式执行/撤消 [英] Do/Undo using command pattern in Python

查看:6606
本文介绍了在Python中使用命令模式执行/撤消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过,使用命令模式是完成do / undo功能的最流行的方法之一。事实上,我已经看到,有可能堆叠一堆动作,扭转它们以达到给定的状态。但是,我不太确定如何在Python和我阅读的大部分教程,可以做到概念,但不显示在Python中的实际实现。

I have read that using command pattern is one of the most popular ways to accomplish do/undo functionality. In fact, I have seen that it's possible to stack a bunch of actions and reverse them in order to reach a given state. However, I'm not quite sure how that can be done in Python and most of the tutorials I have read, dabble into concepts but don't show an actual implementation in Python.

有没有人知道Python中的do / undo功能如何工作?

Does anyone know how do/undo functionality work in Python?

为了参考,这是我的(天真的,可能有错误)代码:

For reference, this is my (naive and probably ridden with errors) code:

# 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

显然,不允许堆栈几个动作撤消。

Obviously, this test doesn't allow stack several actions to undo. Maybe I'm completely mistaken so I would appreciate some help.

推荐答案

下面是一个将命令保存在列表中的实现。 / p>

Here is an implementation keeping the commands in a list.

# 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)
# invoker
class InvokeDrawLines:
    def __init__(self, data):
        self.commandlist = data
    def addcommand(self, command):
        self.commandlist.append(command)
    def draw(self):
        for cmd in self.commandlist:
            cmd.execute_drawing()
    def undocommand(self, command):
        self.commandlist.remove(command)

# receiver
class DrawALine:
    def execute(self, point1, point2):
        print("Draw a line from" , point1, point2)

这篇关于在Python中使用命令模式执行/撤消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆