Friday, November 6, 2020

Memento Pattern

Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later.

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Learning, Oracle Java Exam Prep

Participants

Memento: stores internal state of the Originator object. The memento may store as much or as little of the originator’s internal state as necessary at its originator’s discretion. Protect against access by objects of other than the originator. Mementos have effectively two interfaces. Caretaker sees a narrow interface to the Memento — it can only pass the memento to the other objects. Originator, in contrast, sees a wide interface, one that lets it access all the data necessary to restore itself to its previous state. Ideally, only the originator that produces the memento would be permitted to access the memento’s internal state.

Originator: creates a memento containing a snapshot of its current internal state. Uses the memento to restore its internal state

Caretaker: is responsible for the memento’s safekeeping. Never operates on or examines the contents of a memento.

Code

public class Main {
    public static void main(String[] args) {
        Originator o = new Originator();
        o.setState("On");
        Caretaker c = new Caretaker();
        c.setMemento(o.createMemento());
        o.setState("Off");
        o.setMemento(c.getMemento());
    }
}
public class Originator {
    private String state;
    public String getState() {
        return state;
    }
    public void setState(String state) {
        this.state = state;
        System.out.println("State = " + state);
    }
    public Memento createMemento() {
        return new Memento(state);
    }
    public void setMemento(Memento memento) {
        System.out.println("Restoring state...");
        setState(memento.getState());
    }
}
public class Memento {
    private String state;
    public Memento(String state) {
        this.state = state;
    }
    public String getState() {
        return state;
    }
    public void setState(String state) {
        this.state = state;
    }
}
public class Caretaker {
    private Memento memento;
    public Memento getMemento() {
        return memento;
    }
    public void setMemento(Memento memento) {
        this.memento = memento;
    }
}

Output

State = On
State = Off
Restoring state...
State = On

Related Posts

0 comments:

Post a Comment