python中怎么撤销_在Python中使用命令模式执行/撤消

1586010002-jmsa.png

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.

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))

instantiating as follows:

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()

output:

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.

解决方案

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值