设计模式-备忘录模式

临时存储。也算一种模式?

class Originator{
    private String state="";

    public String getState(){
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }
    public Memento createMemento(){
        return new Memento(this.state);
    }
    public void restoreMemento(Memento memento){
        this.setState(memento.getState());
    }

}
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;
    }
}

class Caretaker{
    private Memento memento;
    public Memento getMemento(){
        return memento;
    }

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

public class MementoTest {
    public static void main(String[] args){
        Originator originator = new Originator();
        originator.setState("state1");
        System.out.println("initial state:"+originator.getState());

        Caretaker caretaker = new Caretaker();
        caretaker.setMemento(originator.createMemento());

        originator.setState("state2");
        System.out.println("change State:"+originator.getState());
        originator.restoreMemento(caretaker.getMemento());
        System.out.println("back:"+originator.getState());
    }
}

你可能感兴趣的:(设计模式-备忘录模式)