class CarMemento(object): brand = '' top_speed = 0 color = '' def __init__(self, brand, top_speed, color): self.brand = brand self.top_speed = top_speed self.color = color def get_saved_attribute(self): return {'brand': self.brand, 'top_speed': self.top_speed, 'color': self.color} class CarOriginator(object): brand = '' top_speed = 0 color = '' def set(self, brand, top_speed, color): self.brand = brand self.top_speed = top_speed self.color = color def save_car_memento(self): print 'Originator: Saving to memento with Brand : {}, Color : {}, Top Speed : {}'.format(self.brand, self.color, self.top_speed) return CarMemento(self.brand, self.top_speed, self.color) def restore_from_memento(self, memento): memento_attribute = memento.get_saved_attribute() self.brand = memento_attribute.get('brand') self.top_speed = memento_attribute.get('top_speed') self.color = memento_attribute.get('color') print 'Originator: Restored from memento with Brand : {}, Color : {}, Top Speed : {}'.format(self.brand, self.color, self.top_speed) class CarCaretaker(object): saved_mementos = [] def add_car_memento(self, memento): self.saved_mementos.append(memento) def get_car_memento(self): return self.saved_mementos.pop() def main(): car_caretaker = CarCaretaker() car_originator = CarOriginator() print 'Main: Hello! I am a car manufacturer director, and my hobby is to design car!' print 'Main: Creating new red lamborghini car with top speed 1000 miles/hr ...' car_originator.set('Lamborghini', 1000, 'red') print 'Main: Save the car information as our baseline' car_caretaker.add_car_memento(car_originator.save_car_memento()) print 'Main: Updating the color to blue to with slower speed of 900 miles/hr to make it cooler and friendlier ...' car_originator.set('Lamborghini', 900, 'blue') print 'Main: I think porsche is more fancy. Let\'s change the brand to Porsche!' car_originator.set('Porsche', 900, 'blue') print 'Main: Ok this looks really great! Let\'s save this car information!' car_caretaker.add_car_memento(car_originator.save_car_memento()) print 'Main: Hmm, If I change the brand to Toyota, I think I can have more sales ...' car_originator.set('Toyota', 120, 'red') print 'Main: Ok I don\'t think Toyota is a good idea. Let\'s revert to our original car!' car_originator.restore_from_memento(car_caretaker.get_car_memento()) print 'Main: Nah! Not this one! I want Lamborghini!' car_originator.restore_from_memento(car_caretaker.get_car_memento()) print 'Main: Ah that should be it!' if __name__ == '__main__': main()
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question