平时遇到word文档编辑忽然电脑断电时,当我们再次打开时,原来的记录状态还在。
ps软件的历史记录等,我们可以使用该记录恢复之前的动作。这些就是备忘录模式的场景
备忘录模式就是提供一个保存对象状态的功能,这样以后就可以将该对象恢复到原来的状态
结构:
源发器类originator: 负责创建一个备忘录memento,用以记录当前时刻自身的内部状态,并可使用备忘录恢复内部状态。
备忘录类memento:负责存储originator对象的内部状态
负责人类caretake:管理备忘录类
/**
* 源发器类
*
*/
public class emp {
//对象状态
private string name;
private int age;
private double salary;
public emp(string name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
//创建备忘录对象,进行备忘操作
public empmemento empmemento() {
return new empmemento(this);
}
//恢复数据
public void recovery(empmemento emp){
this.name = emp.getname();
this.age = emp.getage();
this.salary = emp.getsalary();
}
public string getname() {
return name;
}
public void setname(string name) {
this.name = name;
}
public int getage() {
return age;
}
public void setage(int age) {
this.age = age;
}
public double getsalary() {
return salary;
}
public void setsalary(double salary) {
this.salary = salary;
}
@override
public string tostring() {
return "emp{" +
"name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}
}
/**
* 备忘录类
*/
public class empmemento {
private string name;
private int age;
private double salary;
public empmemento(emp e) {
this.name = e.getname();
this.age = e.getage();
this.salary = e.getsalary();
}
public string getname() {
return name;
}
public void setname(string name) {
this.name = name;
}
public int getage() {
return age;
}
public void setage(int age) {
this.age = age;
}
public double getsalary() {
return salary;
}
public void setsalary(double salary) {
this.salary = salary;
}
}
/**
* 负责人类
* 管理备忘录对象
*/
public class caretaker {
//list ...or
private empmemento memento;
public empmemento getmemento() {
return memento;
}
public void setmemento(empmemento memento) {
this.memento = memento;
}
}
这里如果要记录保存多次(多个备忘点),可以将属性empmemento用容器包装。
public class client {
public static void main(string[] args) {
caretaker taker = new caretaker();
//第一次创建对象
emp emp = new emp("test", 18, 1000);
system.out.println(emp);
//保存一次状态
taker.setmemento(emp.empmemento());
emp.setage(99);
system.out.println(emp);
//恢复状态
emp.recovery(taker.getmemento());
system.out.println(emp);
}
}
emp{name='test', age=18, salary=1000.0}
emp{name='test', age=99, salary=1000.0}
emp{name='test', age=18, salary=1000.0}
process finished with exit code 0
恢复数据成功,即保存状态时成功的。
开发中常用:
棋牌类游戏,悔棋操作
软件的撤销步骤
事务管理回滚等
如对本文有疑问, 点击进行留言回复!!
第三次学JAVA再学不好就吃翔(part88)--ArrayList嵌套ArrayList
使用ffmpeg视频切片并加密和视频AES-128加密后播放
JAVA程序设计:最长重复子串(LeetCode:1044)
LiveGBS国标GB/T28181云端录像分布式录像存储自动清理时移回看录像下载播放
网友评论