软件设计——备忘录模式之多次撤销
改进课堂上的“用户信息操作撤销”实例,使得系统可以实现多次撤销(可以使用HashMap、ArrayList等集合数据结构实现)。
类图:
代码:
Caretaker.java
package com;
import java.util.ArrayList;
public class Caretaker {
private ArrayList<Memento> mementos= new ArrayList<Memento>();
public Memento getMemento(int i)
{
return (Memento)mementos.get(i);
}
public void setMemento(Memento memento)
{
mementos.add(memento);
}
}
UserInfoDTO.java
package com;
/*
* 用户信息类
*/
public class UserInfoDTO {
private String account;
private String password;
private String telNo;
public String getAccount()
{
return account;
}
public void setAccount(String account)
{
this.account=account;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password=password;
}
public String getTelNo()
{
return telNo;
}
public void setTelNo(String telNo)
{
this.telNo=telNo;
}
public Memento saveMemento()
{
return new Memento(account,password,telNo);
}
public void restoreMemento(Memento memento)
{
this.account=memento.getAccount();
this.password=memento.getPassword();
this.telNo=memento.getTelNo();
}
public void show()
{
System.out.println("Account:" + this.account);
System.out.println("Password:" + this.password);
System.out.println("TelNo:" + this.telNo);
}
}
Memento.java
package com;
public class Memento {
private String account;
private String password;
private String telNo;
public Memento(String account,String password,String telNo)
{
this.account=account;
this.password=password;
this.telNo=telNo;
}
public String getAccount()
{
return account;
}
public void setAccount(String account)
{
this.account=account;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password=password;
}
public String getTelNo()
{
return telNo;
}
public void setTelNo(String telNo)
{
this.telNo=telNo;
}
}
Client.java
package com;
public class Client {
public static void main(String a[]){
UserInfoDTO user=new UserInfoDTO();
Caretaker taker = new Caretaker();
user.setAccount("zhangsan");
user.setPassword("123456");
user.setTelNo("13000000000");
System.out.println("状态一:");
taker.setMemento(user.saveMemento());
user.show();
System.out.println("---------------------------");
user.setPassword("111111");
user.setTelNo("13100001111");
System.out.println("状态二:");
user.show();
taker.setMemento(user.saveMemento());
System.out.println("---------------------------");
user.setPassword("222222");
user.setTelNo("13100001111");
System.out.println("状态三:");
user.show();
System.out.println("---------------------------");
System.out.println("回到状态二");
user.restoreMemento(taker.getMemento(1));
user.show();
System.out.println("---------------------------");
System.out.println("回到状态一");
user.restoreMemento(taker.getMemento(0));
user.show();
System.out.println("---------------------------");
}
}