JAVA設計模式之備忘錄模式

JAVA設計模式之備忘錄模式

概念:

備忘錄模式(memento),保存某個對象內部狀態的拷貝,這樣以後就可以將該對象恢復到原先的狀態。

結構

原發器類Originator:保存對象內部狀態

備忘錄類Memento:存儲狀態的拷貝

負責人類CareTake:存儲備忘錄

應用

  1. 棋類開發中的悔棋
  2. 普通軟件的撤銷
  3. 數據庫軟件中,事務管理的回滾操作

類圖

備忘錄模式類圖

代碼

代碼類圖:
僱員信息代碼類圖

 
// 源發器類
public class Emp {
    private String name;
    private int age;

    // 進行備忘操作,返回備忘錄對象
    public EmpMemento memento() {
        return new EmpMemento(this);
    }

    // 進行數據恢復,恢復成指定備忘錄的值
    public void recovery(EmpMemento mmt) {
        this.name = mmt.getName();
        this.age = mmt.getAge();
    }

    public Emp(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
 
// 備忘錄類
public class EmpMemento {
    private String name;
    private int age;

    public EmpMemento(Emp emp) {
        this.name = emp.getName();
        this.age = emp.getAge();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
 
// 負責人類, 負責管理備忘錄
public class CareTake {
    private List empMementoList = new ArrayList<>();//用stack更好,還可以序列化和持久化,存到磁盤,以防丟失

    public void addMemento(EmpMemento empMemento) {
        empMementoList.add(empMemento);
    }

    // 按順序逐個恢復
    public EmpMemento getLastMemento() {
        if (empMementoList.size() <= 0) {
            return null;
        }
        int index = empMementoList.size() - 1;
        EmpMemento result = empMementoList.get(index);
        empMementoList.remove(index);
        return result;
    }

}
 
public class Main {
    public static void main(String[] args) {
        CareTake taker = new CareTake();
        Emp emp = new Emp("55", 15);

        taker.addMemento(emp.memento());
        System.out.println(JSON.toJSONString(emp));
        emp.setAge(16);
        taker.addMemento(emp.memento());
        System.out.println(JSON.toJSONString(emp));
        emp.setAge(17);
        System.out.println(JSON.toJSONString(emp));

        emp.recovery(taker.getLastMemento());
        System.out.println(JSON.toJSONString(emp));

        emp.recovery(taker.getLastMemento());
        System.out.println(JSON.toJSONString(emp));

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章