備忘錄模式

在不破壞封裝性的前提下,捕獲一個對象的內部狀態,並在該對象之外保存這個狀態。

存儲對象狀態:

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 
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章