Restoring the desired state with the memento pattern
Sometimes, it may be useful to consider keeping minimal information about the state of an object in order to continue or restore it. The memento pattern provides this functionality and was described in the GoF’s book.
Motivation
Without breaking encapsulation, the internal state of an object, a memento, needs to be captured and externalized so that the object can later be restored to that state. The memento pattern provides a client function to restore the desired state of an object, a memento, on demand.
Finding it in the JDK
The Date
class that comes with the java.base
module and its java.util
package is a nice implementation of the memento pattern. An instance of a class represents a specific point on a timeline, and the date can be restored to that timeline referring to the calendar or zone used.
Sample code
Let us look at the example of air conditioning in a vehicle. The controller gives us several options...