TechnologyZer
technologyzer.com

Memento Design Pattern

Memento/Snapshot Design Pattern is a behavioral pattern that allows capturing and restoring an object’s internal state without violating encapsulation. It involves three main components:

  1. Originator: The object whose state needs to be saved.
  2. Memento: An object that stores the state of the originator.
  3. Caretaker: The object that keeps track of multiple mementos and can restore the originator’s state from them.

This pattern is useful in scenarios where you need to implement undo mechanisms, restore objects to previous states, or provide checkpoints in an application’s execution.

public class Memento {
    private String state;

    public Memento(String state) {
        this.state = state;
    }

    public String getState() {
        return state;
    }
}

class Originator {
    private String state;

    public void setState(String state) {
        this.state = state;
    }

    public String getState() {
        return state;
    }

    public Memento saveStateToMemento() {
        return new Memento(state);
    }

    public void getStateFromMemento(Memento memento) {
        state = memento.getState();
    }
}

public class Caretaker {
    private final Deque<Memento> stackOfMemento = new ArrayDeque<>();

    public void saveMemento(Memento memento) {
        stackOfMemento.push(memento);
    }

    public Memento retrieveMemento() {
        return stackOfMemento.pop();
    }
}

public class Main {
    public static void main(String[] args) {
        Originator originator = new Originator();
        Caretaker caretaker = new Caretaker();

        // Setting the state and saving it
        originator.setState("State 1");
        caretaker.saveMemento(originator.saveStateToMemento());

        // Changing the state
        originator.setState("State 2");

        // Retrieving the saved state and restoring it
        originator.getStateFromMemento(caretaker.retrieveMemento());

        System.out.println("Current State: " + originator.getState()); // Output: Current State: State 1
    }
}

Leave a Comment