Do/Undo using command pattern in Python

后端 未结 2 581
北荒
北荒 2021-01-16 15:05

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 acti

2条回答
  •  独厮守ぢ
    2021-01-16 15:53

    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)
    

提交回复
热议问题