本次實驗屬於模仿型實驗,透過本次實驗學生將掌握以下內容:
1、理解備忘錄模式的動機,掌握該模式的結構;
2、能夠利用備忘錄模式解決實際問題。
[實驗任務一]:多次撤銷
改進課堂上的“使用者資訊操作撤銷”例項,使得系統可以實現多次撤銷(可以使用HashMap、ArrayList等集合資料結構實現)。
實驗要求:
1. 畫出對應的類圖;
2. 提交原始碼;
3. 注意程式設計規範。
1、類圖
1、原始碼
package org.example;
import java.util.ArrayList;
import java.util.List;
public class Caretaker {
private List<Memo> list = new ArrayList<>();
public void setMemo(Memo m){
list.add(m);
}
public Memo getMemo(){
Memo m = list.get( list.size() - 2 );
list.remove( list.size() - 2 );
return m;
}
}
package org.example;
public class Client {
public static void main(String[] args) {
User user = new User();
Caretaker caretaker = new Caretaker();
user.setId("20223794");
user.setPassword("123456");
caretaker.setMemo(user.saveState());
System.out.println("狀態一");
user.show();
System.out.println("************************************************************");
user.setId("20223794");
user.setPassword("dadvgfb");
caretaker.setMemo(user.saveState());
System.out.println("狀態二");
user.show();
System.out.println("************************************************************");
user.setId("20223794");
user.setPassword("safdvfv");
caretaker.setMemo(user.saveState());
System.out.println("狀態三");
user.show();
System.out.println("************************************************************");
System.out.println("逐步撤銷操作:");
System.out.println("恢復到狀態二");
user.restoreState(caretaker.getMemo());
user.show();
System.out.println("************************************************************");
System.out.println("恢復到狀態一");
user.restoreState(caretaker.getMemo());
user.show();
}
}
package org.example;
public class Memo {
private String id;
private String password;
public Memo(String id, String password) {
this.id = id;
this.password = password;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package org.example;
public class User {
private String id;
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Memo saveState(){
return new Memo(id,password);
}
public void restoreState(Memo m){
this.id = m.getId();
this.password = m.getPassword();
}
public void show(){
System.out.println("id:" + this.id);
System.out.println("password:" + this.password);
}
}
2、執行截圖