备忘录模式

来源:互联网 发布:乐视视频mac 编辑:程序博客网 时间:2024/06/17 13:03

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

存储对象状态:

public class Memento {   private String state;   public Memento(String state){      this.state = state;   }   public String getState(){      return state;   }    }

存储对象列表:

import java.util.ArrayList;import java.util.List;public class CareTaker {   private List<Memento> mementoList = new ArrayList<Memento>();   public void add(Memento state){      mementoList.add(state);   }   public Memento get(int index){      return mementoList.get(index);   }}

//

public class Originator {    //这是一个要保存的状态    private String state = 90;   //备忘录管理对象    private Caretaker c = new Caretaker();   public void setMemento(){    Memento memento = new c.getMemento();    state = memento.getState();    System.out.println("the state is " + state + "now");    }    public }
原创粉丝点击