编程语言
首页 > 编程语言> > JAVA设计模式(行为型)------ 备忘录模式

JAVA设计模式(行为型)------ 备忘录模式

作者:互联网

在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。

public class Memento_Main {
    public static void main(String[] args) {
        Originator originator = new Originator();
        MementoManager mementoManager = new MementoManager();
        originator.setState("First");
        Memento firstMemento = originator.saveMemento();
        mementoManager.add(firstMemento);
        originator.setState("second");
        Memento secondMemento = originator.saveMemento();
        mementoManager.add(secondMemento);
        originator.setState("third");
        Memento thirdMemento = originator.saveMemento();
        mementoManager.add(thirdMemento);

        System.out.println(mementoManager.get(0).getState());
        System.out.println(mementoManager.get(1).getState());
        System.out.println(mementoManager.get(2).getState());

    }
}

class Originator{
    private String state;

    public String getState() {
        return state;
    }

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

    public Memento saveMemento(){
        return new Memento(this.state);
    }
    public void getStateFromMemento(Memento memento){
        if (memento != null){
            this.state = memento.getState();
        }
    }
}

class Memento{
    private String state;

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

    public String getState() {
        return state;
    }
}
class MementoManager{
    private List<Memento> mementos = new CopyOnWriteArrayList<>();
    public void add(Memento memento){
        if (memento != null)
            mementos.add(memento);
        return;
    }
    public Memento get(int index){
        return mementos.get(index);
    }
}

标签:originator,JAVA,String,mementoManager,备忘录,state,设计模式,public,Memento
来源: https://blog.csdn.net/wjh874024173/article/details/94548415