1. 程式人生 > 實用技巧 >Web快取相關知識整理

Web快取相關知識整理

Memento模式比較適用於功能比較複雜的,但需要維護或記錄屬性歷史的類,或者需要儲存的屬性只是眾多屬性的一小部門時,

Originator可以根據儲存的Memento資訊還原到前一狀態

程式碼部分:

 1 /**
 2  * Originator(發起人):負責建立備忘錄Memento,用來記錄當前時刻它的內部狀態,
 3  * 並可以使用備忘錄恢復內部狀態,Originator可以根據需要決定Memento儲存Originator
 4  * 的哪些內部狀態
 5  */
 6 public class Originator {
 7     private String state;
8 9 public String getState() { 10 return state; 11 } 12 13 public void setState(String state) { 14 this.state = state; 15 } 16 17 /**建立備忘錄,將當前需要儲存的資訊匯入並例項化出一個Memento物件 */ 18 public Memento createMemento(){ 19 return new Memento(state); 20 } 21
/** 22 * 恢復備忘錄,將Memento資料匯入並恢復資料 23 */ 24 public void setMemento(Memento memento){ 25 state = memento.getState(); 26 } 27 28 public void show(){ 29 System.out.println("state===="+state); 30 } 31 }
Originator

 1 /**
 2  * Memento(備忘錄):負責儲存Originator物件的內部狀態,並可防止Originator以外
3 * 的其它物件訪問備忘錄Memento,備忘錄有兩個介面,Garetaker只能看到備忘錄的窄介面, 4 * 它只是將備忘錄傳遞給其它物件,Originator是一個寬介面,允許它訪問到先前狀態所需的所有資料 5 */ 6 public class Memento { 7 private String state; 8 9 public String getState() { 10 return state; 11 } 12 13 public void setState(String state) { 14 this.state = state; 15 } 16 17 public Memento(String state) { 18 super(); 19 this.state = state; 20 } 21 22 public Memento() { 23 super(); 24 } 25 }
Memento
 1 /**
 2  * Garetaker(管理者):負責儲存好備忘錄Memento,
 3  * 不能對備忘錄內容進行操作或檢查
 4  */
 5 public class Garetaker {
 6     private Memento memento;
 7 
 8     public Memento getMemento() {
 9         return memento;
10     }
11 
12     public void setMemento(Memento memento) {
13         this.memento = memento;
14     }
15 }
Garetaker
 1 public class MementOTest {
 2     public static void main(String[] args) {
 3         Originator or = new Originator();
 4         or.setState("ON");
 5         or.show();
 6         
 7         Garetaker ga = new Garetaker();
 8         ga.setMemento(or.createMemento());
 9         or.setState("OFF");
10         or.show();
11         
12         or.setMemento(ga.getMemento());
13         or.show();
14     }
15 }
test