ich versuche gerade für mein Projekt einen Undo-Manager zu implementieren. Hier könnt ihr einen ersten Entwurf dafür sehen:
Code: Alles auswählen
class UndoManager(object):
def __init__(self):
"""
Constructor for UndoManager.
"""
self.clear()
def add(self, undoCommand, undoArgs=(), \
redoCommand=None, redoArgs=()):
"""
Add a undo/redo command to the undo stack.
"""
if self.LOCK:
return
command = {
'Undo': undoCommand,
'UndoArgs': undoArgs,
'Redo': redoCommand,
'RedoArgs': redoArgs
}
self._undoStack.append(command)
self._redoStack = []
def undo(self):
"""
Pop latest command from _undoStack and call it. If there es a redo
action, then add it to the _redoStack
"""
command = self._undoStack.pop()
self.LOCK = True
command['Undo'](*command['UndoArgs'])
self.LOCK = False
if command['Redo'] is not None:
self._redoStack.append(command)
def redo(self):
"""
Pop latest command from _redoStack and call it. Readd the action to the
_undoStack.
"""
command = self._redoStack.pop()
self.LOCK = True
command['Redo'](*command['RedoArgs'])
self.LOCK = False
self._undoStack.append(command)
def clear(self):
"""
Clear the _undoStack and _redoStack.
"""
self._undoStack = []
self._redoStack = []
self.LOCK = False
Code: Alles auswählen
from undo import UndoManager
class A:
def __init__(self):
self.x = 0
self.undoManager = UndoManager()
def add(self, value):
self.x += value
#inform undoManager
self.undoManager.add(self.subtract, (value,), self.add, (value,))
def subtract(self, value):
self.x -= value
#inform undoManager
self.undoManager.add(self.add, (value,), self.subtract, (value,))
Gruß, Rekrul