设计模式---备忘录模式

备忘录模式:
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可以将该对象恢复到以前保存的状态。

public class Memento {
    private String state;

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

    public String getState() {
        return state;
    }
}
public class Originator {
    private String state;

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

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

    public String getState() {
        return state;
    }

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

    public void show() {
        System.out.println("State::" + state);
    }
}

public class Manager {
    private Memento memento;

    public Memento getMemento() {
        return memento;
    }

    public void setMemento(Memento memento) {
        this.memento = memento;
    }
}
public class MementoDemo{
    public static void main(String[] args) {
        Originator originator = new Originator();
        originator.setState("ON");
        originator.show();

        Manager manager = new Manager();
        Memento memento = originator.createMemento();
        manager.setMemento(memento);

        originator.setState("OFF");
        originator.show();

        originator.setMemento(manager.getMemento());
        originator.show();

    }
}

你可能感兴趣的:(设计模式)