行为型模式 备忘录模式

1 在不破坏封装的前提下,捕获一个对象的内部状态,
并在该对象之外保存这个状态,这样可以在以后将对象恢复到原先保存的状态。

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 Originator{
    private String state;
    public Originator(String state) {
        this.state = state;
    }
    public Memento saveToList(){
        return new Memento(state);
    }
    public void getFromList(Memento memento){
        state = memento.getState();
    }
}
class CareList{
     private List<Memento> mementos = new ArrayList<Memento>();
     public void setMementos(Memento memento){
         mementos.add(memento);
     }
     public Memento getMementos(int index){
         return mementos.get(index);
     }
}
public class Test{
    public static void main(String[] args){
        CareList careList = new CareList();
        Originator originator = new Originator("state1");
        careList.setMementos(originator.saveToList());
        System.out.println(careList.getMementos(0).getState());
    }
}

猜你喜欢

转载自blog.csdn.net/qq_28197211/article/details/80482521