天天看點

某系統提供了使用者資訊操作子產品,使用者可以修改自己的各項資訊。為了使操作過程更加人性化,現使用備忘錄模式對系統進行改進,使得使用者在進行了錯誤操作之後可以恢複到操作之前的狀态。使用者資訊中包含賬号、密碼、電話

繪制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);//初始化客戶1
    System.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());  
  }
}