Memo mode , Without breaking the closure , Capture the internal state of an object , And save the state outside the object . In this way, the object can be restored to the original saved state later .
Simply speaking , That is, we can record a certain state during the operation , Restore the current state when encountering errors , This is designed to handle exceptions in business processes .
advantage :
shortcoming :
Entity role :
Originator( Originator ): Responsible for creating a Memento( Memorandum ), It is used to record the internal state of the current moment , And you can use the memo to restore the internal state .Originator It's up to you to decide Memento What internal states are stored .
Memento( Memorandum ): Responsible for the storage Originator The internal state of an object , And can prevent Originator Access memo for other objects . The memo has two interfaces :
Caretaker( managers ): be responsible for Memento, Not right Memento Access or operate on the content of .
class AddNumber:
def __init__(self):
self.start = 1
def add(self, number):
self.start += number
print(self.start)
class Memento:
""" Memorandum """
def backups(self, obj=None):
""" Set backup method :param obj: :return: """
self.obj_dict = copy.deepcopy(obj.__dict__)
print(" The backup data :{}".format(self.obj_dict))
def recovery(self, obj):
""" Restore backup method :param obj: :return: """
obj.__dict__.clear()
obj.__dict__.update(self.obj_dict)
return obj
if __name__ == '__main__':
test = AddNumber()
memento = Memento()
for i in [1, 2, 3, 'n', 4]:
if i == 2:
memento.backups(test)
try:
test.add(i)
except TypeError as e:
print(e)
print(test.start)
memento.recovery(test)
print(test.start)