绘制UML类图
信息的初始化建立备忘录
备忘录的创建过程,就是通过构造函数的形式将一个类中的属性赋值给另外一个类里边的属性。实现原始数据的保存。在恢复原始数据时,通过创建另外一个类的对象,通过对象调用属性。然后赋值给这边类里的属性。
package com.zheng;public class Originator { // 原始数据private String name; // 姓名private String pwd; // 密码private double num; // 电话//初始化客户信息public Originator(String name,String pwd,double num) {this.name=name;this.pwd=pwd;this.num=num;}//创建一个备忘录对象public Memento save() {return new Memento(this.name,this.pwd,this.num);//将原始数据的值保存在备忘录里边}//恢复状态public void restore(Memento memento) {this.name=memento.getName();//从备忘录里边取值给原始数据this.pwd=memento.getPwd();this.num=memento.getNum();}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}public double getNum() {return num;}public void setNum(double num) {this.num = num;}}
保存客户信息
package com.zheng;public class Memento {private String name; // 姓名private String pwd; // 密码private double num; // 电话//初始化客户信息public Memento(String name,String pwd,double num) {this.name=name;this.pwd=pwd;this.num=num;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}public double getNum() {return num;}public void setNum(double num) {this.num = num;}}
调用备忘录里边的属性返回给保存的数据
package com.zheng;public class MementoCaretaker {private Memento me;//备忘录对象public Memento getMemento() {return me;}public void setMemento(Memento me) {this.me=me;}}
测试端
package com.zheng;public class Client {public static void main(String[] args) {// TODO 自动生成的方法存根MementoCaretaker mc=new MementoCaretaker();//管理者对象Originator cus1=new Originator("小明","12345",12345);//初始化客户1System.out.println("状态一:");display(cus1);mc.setMemento(cus1.save());//保存状态System.out.println("----------------------------------");System.out.println("状态二:");cus1.setPwd("22222");cus1.setNum(99999);display(cus1);System.out.println("----------------------------------");System.out.println("状态二回到状态一:");cus1.restore(mc.getMemento());//恢复状态display(cus1);}public static void display(Originator o) {System.out.println("账户:"+o.getName()+"\n密码:"+o.getPwd()+"\n电话:"+o.getNum()); }
}
运行截图