适用场景
需要记录的源类
package design.behavior.memento; public class Stats { private String name; private String age; private String money; public Stats(String name, String age, String money) { this.name = name; this.age = age; this.money = money; } /** * 数据备份 * @return */ public Memento memento(){ return new Memento(this); } /** * 恢复 * @param memento * @return */ public Stats recovery(Memento memento){ return new Stats(memento.getName(),memento.getAge(),memento.getMoney()); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getMoney() { return money; } public void setMoney(String money) { this.money = money; } }
备忘录(又叫便利贴纸)
package design.behavior.memento; public class Memento { private String name; private String age; private String money; Memento(Stats stats){ this.name=stats.getName(); this.age=stats.getAge(); this.money=stats.getMoney(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getMoney() { return money; } public void setMoney(String money) { this.money = money; } }
CareTask存放备忘录的地方
package design.behavior.memento; import java.util.LinkedList; public class CareTask { private LinkedList<Memento> linkedList = new LinkedList(); public Memento getMemento(){ if(linkedList.size()>0){ return linkedList.pop(); } return null; } public void setMemento(Memento memento){ linkedList.push(memento); } }
客户端client
package design.behavior.memento; /** * 备忘录模式-记录每次操作的状态,用于回滚 */ public class Client { public static void main(String[] args) { CareTask careTask = new CareTask(); Stats yyj = new Stats("yyj", "10", "2000"); careTask.setMemento(yyj.memento()); showStats(yyj); yyj.setMoney("11000"); yyj.setAge("28"); careTask.setMemento(yyj.memento()); showStats(yyj); yyj.setMoney("21000"); yyj.setAge("38"); showStats(yyj); yyj = yyj.recovery(careTask.getMemento()); showStats(yyj); yyj = yyj.recovery(careTask.getMemento()); showStats(yyj); } private static void showStats(Stats stats){ System.out.println(String.format("我的名字:%s,我的年龄%s,我的工资%s" ,stats.getName(),stats.getAge(),stats.getMoney())); } }
其实备忘录模式某种意义上就是把对象clone一次,放在linkedList中,每次操作都Push进去,回滚就把状态对象pop出来