Share This Article
The memento pattern in Ruby is a design pattern that allows you to save an object’s state and restore it later.
This can be useful for things like undo/redo or for storing the state of an object so that you can resume from that point if the program crashes.
This article will implement the memento pattern using a simple console calculator as an example.
Example
We’ll start by creating a Calculator
class with two methods: add
and subtract
.
class Calculator
attr_reader :result
def initialize
@result = 0
end
def add(number)
@result += number
end
def subtract(number)
@result -= number
end
end
These methods are pretty simple, add
just adds a number to the @result
instance variable, and subtract
does the same thing but with subtraction.
Now we’re going to create a CalculatorMemento
class to store the state of our Calculator
.
It will have two methods: save
and restore
.
The save
method will accept a Calculator
object as an argument and store its state.
The restore
method will do the opposite; it will accept a Calculator
object and restore its state from the memento.
class CalculatorMemento
def initialize(calculator)
@calculator = calculator
@state = calculator.result
end
def save
@state
end
def restore
@calculator.instance_variable_set(:@result, @state)
end
end
And that’s it! We now have a working implementation of the memento pattern.
Let’s see it in action:
calculator = Calculator.new
calculator.add(10)
puts calculator.result
# 10
calculator.subtract(5)
puts calculator.result
# 5
memento = CalculatorMemento.new(calculator)
calculator.add(10)
puts calculator.result
# 15
memento.restore
puts calculator.result
# 5
First, we create a Calculator
object and add 10 to it.
Then we subtract 5, and the result is 5.
Next, we create a CalculatorMemento
object, and pass our calculator to it.
Then we add 10 to the calculator again, and the result is 15.
Finally, we call the restore
method on the memento, which restores the calculator’s state and the result is 5 again.
Conclusion
In this article, you’ve learned how to use the memento pattern to save the state of an object so that you can restore it later.
You’ve also learned how to create a simple console calculator that uses the memento pattern to undo and redo operations.
If you want to learn more about the memento pattern, I recommend reading the following articles: