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

备忘录模式也是行为模式的一种,主要是提供一种保存内部状态的方法,方便在合适的时候恢复。简单实现:

备忘录实体类:

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 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 MementoManager {
    private ArrayList mementoList = new ArrayList<>();

    public void add(Memento state){
        mementoList.add(state);
    }

    public Memento get(int index){
        return mementoList.get(index);
    }
}

测试类

    public static void main(String[] args) {
        Originator originator = new Originator();
        MementoManager manager = new MementoManager();
        originator.setState("state 1");
        originator.setState("state 2");
        manager.add(originator.saveStateToMemento());
        originator.setState("state 3");
        manager.add(originator.saveStateToMemento());
        originator.setState("state 4");
        System.out.println(originator.getState());
        System.out.println(manager.get(0).getState());
    }

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