1、Memento.java
package com.ssm.cts.pattern.memento; public class Memento { private String state = ""; public Memento(String _state) { this.state = _state; } public String getState() { return state; } public void setState(String state) { this.state = state; } }
2、Job.java
package com.ssm.cts.pattern.memento; public class Job { private String state = ""; public void changeState() { this.state = "测试新玩法"; } public String getState() { return state; } public void setState(String state) { this.state = state; } // 保留备份 public Memento createMemento() { return new Memento(this.state); } // 恢复备份 public void restoreMemento(Memento _memento) { this.setState(_memento.getState()); } }
3、Demo.java
package com.ssm.cts.pattern.memento; public class Demo { // 测试 public static void main(String[] args) { Job job = new Job(); // 初始化当前状态 job.setState("原始状态"); System.out.println(job.getState()); // 记录当前状态 Memento mem = job.createMemento(); // 状态改变 job.changeState(); System.out.println(job.getState()); // 恢复原状 job.restoreMemento(mem); System.out.println(job.getState()); } }