备忘录模式是一种行为型设计模式,其主要用于保存对象状态,以便在需要时恢复其先前的状态。该模式将对象状态封装到备忘录对象中,使得该对象的状态可以在不破坏其封装性的情况下被恢复。
备忘录模式由三个主要组件组成:
总之,备忘录模式是一种非常有用的设计模式,可以方便地实现对象状态的保存和恢复,保护对象状态的封装性,并简化原发器对象的代码。但是,在使用备忘录模式时,需要权衡其优缺点,并根据实际情况选择合适的方案。
传统设计模式讲解时使用的示例代码,大都采用与读者日常生活接解的业务系统没有多大关联关系。以致大部分读者无法做到学以致用,学完就忘记。本文采用使用日常生活中随处可见的优惠券业务来编写实现代码:
在电商平台中,备忘录模式可以用于保存用户购物车的状态。具体来说,用户的购物车可以被视为一个发起人对象,它的状态包括购物车中的商品数量、商品价格、商品折扣等信息。 当用户在购物车中添加或删除商品时,购物车对象会创建一个备忘录对象,并将当前状态保存在备忘录对象中。备忘录对象由管理者对象保存,以便在需要时可以将购物车状态恢复到先前的状态。 以下是一个基于Java实现的备忘录模式示例代码,该代码演示了如何使用备忘录模式保存购物车的状态。
public class ShoppingCartMemento {
private int itemCount;
private double totalPrice;
public ShoppingCartMemento(int itemCount, double totalPrice) {
this.itemCount = itemCount;
this.totalPrice = totalPrice;
}
public int getItemCount() {
return itemCount;
}
public double getTotalPrice() {
return totalPrice;
}
}
public class ShoppingCart {
private int itemCount;
private double totalPrice;
public void addItem(int count, double price) {
itemCount += count;
totalPrice += count * price;
}
public void removeItem(int count, double price) {
itemCount -= count;
totalPrice -= count * price;
}
public ShoppingCartMemento save() {
return new ShoppingCartMemento(itemCount, totalPrice);
}
public void restore(ShoppingCartMemento memento) {
itemCount = memento.getItemCount();
totalPrice = memento.getTotalPrice();
}
public String toString() {
return "Item count: " + itemCount + ", Total price: " + totalPrice;
}
}
public class ShoppingCartCaretaker {
private ShoppingCartMemento memento;
public void saveMemento(ShoppingCartMemento memento) {
this.memento = memento;
}
public ShoppingCartMemento getMemento() {
return memento;
}
}
public class Main {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
ShoppingCartCaretaker caretaker = new ShoppingCartCaretaker();
// 添加商品
cart.addItem(2, 100);
System.out.println("After adding items: " + cart.toString());
// 保存状态
ShoppingCartMemento memento = cart.save();
caretaker.saveMemento(memento);
// 删除商品 cart.removeItem(1, 100);
System.out.println("After removing items: " + cart.toString());
// 恢复状态 memento = caretaker.getMemento();
cart.restore(memento);
System.out.println("After restoring items: " + cart.toString());
}
}