多次撤销
改进课堂上的“用户信息操作撤销”实例,使得系统可以实现多次撤销(可以使用HashMap、ArrayList等集合数据结构实现)。
实验要求:
1. 提交源代码;
Caretaker.java
package ruanshe20;
public class Caretaker
{
private Memento[] array = null;
private int index;
private Memento memento;
public Memento getMemento()
{
return memento;
}
public void setMemento(Memento memento)
{
this.memento=memento;
}
public Caretaker(){
array = new Memento[10];
index = 0;
}
public void addMemento(Memento Memento){
array[index++] = Memento;
}
public Memento preMemento(){
Memento pop = null;
try {
pop = array[--index];
} catch (Exception e) {
e.printStackTrace();
}
return pop;
}
}
main.java
package ruanshe20;
public class main {
public static void main(String args[]) {
UserinfoDTO user = new UserinfoDTO();
Caretaker c = new Caretaker();
user.setAccount("九十七");
user.setPassword("hashdhasdh123");
user.setTelNo("asdad132");
System.out.println("状态一:");
user.show();
c.addMemento(user.saveMemento());
System.out.println("-----------------");
user.setPassword("489a231");
user.setTelNo("7894561");
System.out.println("状态二:");
user.show();
c.addMemento(user.saveMemento());
System.out.println("-----------------");
user.setPassword("16548921");
user.setTelNo("4653132");
System.out.println("状态三:");
user.show();
System.out.println("-----------------");
user.restoreMemento(c.preMemento());
System.out.println("回到状态二:");
user.show();
System.out.println("-----------------");
user.restoreMemento(c.preMemento());
System.out.println("回到状态一:");
user.show();
System.out.println("-----------------");
}
}
Memento.java
package ruanshe20;
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;
}
}
UserinfoDTO.java
package ruanshe20;
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("账号是" + this.account);
System.out.println("密码是" + this.password);
System.out.println("电话是" + this.telNo);
}