免責事項:この記事はブロガーオリジナル記事ですが、許可ブロガーなく再生してはなりません。https://blog.csdn.net/qq_40646143/article/details/85532310
メモモードコアは、次のとおりです。
- 後であなたが元の状態にオブジェクトを返すことができるように、オブジェクトの内部状態のコピーを保存します。
実装するためのコードを使用して次に、
1)主要なクラスを作成します
/**
* 原发器类
*/
public class Emp {
private String name;
private int age;
private int salary;
/**
* 进行备份操作,并返回备忘录对象
* @return
*/
public EmpMemento memento(){
return new EmpMemento(this);
}
/**
* 回滚到上一个保存节点
* @param empMemento
*/
public void recovery(EmpMemento empMemento){
this.name=empMemento.getName();
this.age=empMemento.getAge();
this.salary=empMemento.getSalary();
}
public Emp(String name, int age, int salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
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 int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
2)メモクラスを作成します。
/**备忘录类
* @author 晓电脑
*/
public class EmpMemento {
private String name;
private int age;
private int salary;
/**
* 进行备份
* @param emp
*/
public EmpMemento(Emp 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 int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
3)人間の責任を作成
import java.util.ArrayList;
import java.util.List;
/**负责人类 负责管理备忘录对象
* @author 晓电脑
*/
public class CareTasker {
private EmpMemento empMemento;
//如果保存很多次
//private List<EmpMemento> lists = new ArrayList<>();
public EmpMemento getEmpMemento() {
return empMemento;
}
public void setEmpMemento(EmpMemento empMemento) {
this.empMemento = empMemento;
}
}
4)テスト用クライアントを作成します。
public class Client {
public static void main (String[] args) {
CareTasker tasker = new CareTasker();
//创建一个对象
Emp emp = new Emp("zs", 18, 2800);
System.out.println("第一次打印:" + emp.getName() + emp.getAge() + emp.getSalary());
//进行备份
tasker.setEmpMemento(emp.memento());
emp.setName("www");
emp.setAge(19);
emp.setSalary(5000);
System.out.println("第二次打印:" + emp.getName() + emp.getAge() + emp.getSalary());
System.out.println("################");
emp.recovery(tasker.getEmpMemento());
System.out.println("第三次打印:" + emp.getName() + emp.getAge() + emp.getSalary());
}
}
業績
図クラスのUML
メモは、比較的長い時間をポイントすると:
覚書プッシュ
public class CareTaker{
private Memento memento;
private Stack<Memento> stacks = new Stack<Memento>();
}
- メモ対象配列と持続複数の
一般的なシナリオの開発:
- 一般的なソフトウェア、元に戻します
- データベース・ソフトウェア、物事の管理、ロールバック
- PSソフト、歴史