设计模式-备忘录模式

发布于:2025-07-03 ⋅ 阅读:(26) ⋅ 点赞:(0)

1.需要的类

一个备忘录类:用来set,get属性
一个记录者类:操作备忘录里的属性,以及创建备忘录
一个管理员类:通过记录者创建备忘录,并将其记录
在这里插入图片描述

2.实现代码

属性类(备忘录里的属性)

/**
 * 目标类,存储商品金额和变更时间
 */
public class CashFile {

    //商品金额
    private double money;

    //变更时间
    private Date date;

    public CashFile(double money, Date date) {
        this.money = money;
        this.date = date;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }

}

备忘录类

/**
 * 备忘录类
 */
public class CashMemento {
    private CashFile cashFile;
    public CashMemento(CashFile cashFile)
    {
        this.cashFile = cashFile;
    }
    public CashFile getCashFile()
    {
        return cashFile;
    }
    public void setCashFile(CashFile cashFile)
    {
        this.cashFile = cashFile;
    }
}

记录者类

/**
 * 记录者类
 */
public class CashOriginator {
    private CashFile cashFile;

    public CashFile getCashFile() {
        return cashFile;
    }

    public void setCashFile(CashFile cashFile) {
        this.cashFile = cashFile;
    }
    public CashMemento createMemento() {
        return new CashMemento(cashFile);
    }
    public void restoreMemento(CashMemento cashMemento) {
        this.cashFile = cashMemento.getCashFile();
    }
}

管理员类

/**
 * 管理员
 */
public class Admin {
    private int cursorIndex;

    private List<CashMemento> cashMementoList = new ArrayList<>();

    public void append(CashMemento cashMemento){
        cashMementoList.add(cashMemento);
        cursorIndex++;
    }
    public CashMemento undo(){
        if(cursorIndex > 0){
            cursorIndex--;
            return cashMementoList.get(cursorIndex);
        }
        return cashMementoList.get(0);
    }
    public CashMemento redo(){
        if(cursorIndex < cashMementoList.size()-1){
            cursorIndex++;
            return cashMementoList.get(cursorIndex);
        }
        return cashMementoList.get(cashMementoList.size()-1);
    }
}

使用

@SpringBootApplication
public class MemoApplication {

    public static void main(String[] args) {
        Admin admin = new Admin();
        CashOriginator originator = new CashOriginator();
        originator.setCashFile(new CashFile(500,new Date()));
        admin.append(originator.createMemento());
        originator.setCashFile(new CashFile(400,new Date()));
        admin.append(originator.createMemento());
        originator.setCashFile(new CashFile(300,new Date()));
        admin.append(originator.createMemento());
        System.out.println(admin.undo().getCashFile().getMoney());
        System.out.println(admin.undo().getCashFile().getMoney());
        System.out.println(admin.undo().getCashFile().getMoney());
        System.out.println(admin.redo().getCashFile().getMoney());
    }

}