Behavioral Patterns - Memento Pattern Exercise
The Memento Pattern is used to record the internal state of an object. It is used to create a state machine and also makes undo or redo operation very easy with this pattern. In this exercise, we will use a scenario of account and account manager to understand the components of this pattern.
Reading Materials
- https://en.wikipedia.org/wiki/Memento_pattern (15 minutes reading)
Practice Materials
- Use the Memento Pattern to support an account manager to do save and roll back operations for his managed accounts.
Components:
- Originator (The object whose state will be saved as a memento) -
Account
- Memento (The object that represent the saved state from its originator) -
AccountMemento
- Caretaker (The object that keep the immutable state of mementos) -
AccountManager
- Client (The entry point of the application that will run the given scenario) -
App
Tip
- Not all states of the originator have to be saved to a memento object.
- To implement rollback or revert in the
AccountManager
, a stack could be used to keep track of the entire memento history. Account.deposit
orAccount.withdraw
could be created to change theAccount.balance
Solution
Questions to discuss
- What are the common use cases to apply a Memento Pattern?
- What are the similarities and differences of the Memento Pattern and the Command Pattern?
Comments
Post a Comment