zoukankan      html  css  js  c++  java
  • 18.备忘录模式

    备忘录模式就是保存某个对象内部状态的拷贝,这样就可以将该对象恢复为原来的对象。

    结构:

      源发器类;备忘录类;负责人类;

    //源发器类
    public
    class Emo { private String ename; private int age; private String salary; //进行备忘录操作 public EmpMemento memento(){ return new EmpMemento(this); } //进行数据恢复 public void recovery(EmpMemento em){ this.ename = em.getEname(); this.age = em.getAge(); this.salary = em.getSalary(); } public Emo(String ename, int age, String salary) { super(); this.ename = ename; this.age = age; this.salary = salary; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSalary() { return salary; } public void setSalary(String salary) { this.salary = salary; } }
    //备忘录类
    public class EmpMemento { private String ename; private int age; private String salary; public EmpMemento(Emo e){ this.ename = e.getEname(); this.age = e.getAge(); this.salary = e.getSalary(); } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSalary() { return salary; } public void setSalary(String salary) { this.salary = salary; } }
    //负责人类
    public class CareTake { private EmpMemento empMemento;//可以将其保存到容器中 比如Stack public EmpMemento getEmpMemento() { return empMemento; } public void setEmpMemento(EmpMemento empMemento) { this.empMemento = empMemento; } } public class Client { public static void main(String[] args) { CareTake careTake = new CareTake(); Emo emo = new Emo("kobe", 23, "15000"); System.out.println("第一次打印:"+emo.getEname()+" "+emo.getAge()+" "+emo.getSalary()); careTake.setEmpMemento(emo.memento()); emo.setEname("james"); emo.setAge(33); emo.setSalary("15000"); System.out.println("第二次打印:"+emo.getEname()+" "+emo.getAge()+" "+emo.getSalary()); emo.recovery(careTake.getEmpMemento()); System.out.println("第三次打印:"+emo.getEname()+" "+emo.getAge()+" "+emo.getSalary()); } } 运行结果: 第一次打印:kobe 23 15000 第二次打印:james 33 18000 第三次打印:kobe 23 15000

    应用场景:

    棋类游戏中:悔棋

    普通软件中:撤销操作

    数据库软件中:回滚操作

  • 相关阅读:
    古典密码仿射密码Affine
    git 修改远程仓库地址的方法
    git 修改已经 commit 的用户名和邮箱
    git 调整commit之间的顺序
    Go 逃逸分析
    docker 镜像中的 @sha256:cbeaf907fc78ac97ce7b625e4bf0de16e3ea725daf6b04f930bd14c67c671ff9 (digest)是什么意思
    Docker镜像列表中的<none>:<none>是什么镜像
    github 下fork后如何同步源的新更新内容
    SQL 中 exists 的用法
    OLEDB的Excel的IMEX和HDR是什么意思
  • 原文地址:https://www.cnblogs.com/menbo/p/10193011.html
Copyright © 2011-2022 走看看