Memento模式在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
类图:
案例: 购物的时候你可以临时改变送货地址和联系电话,通过Memento模式恢复到原始的送货地址和联系电话。
public class Buyer { private String name; private String phoneNum; private String address; public Buyer(String name, String phoneNum, String address) { this.name = name; this.phoneNum = phoneNum; this.address = address; } public String getName() { return name; } public String getPhoneNum() { return phoneNum; } public void setPhoneNum(String phoneNum) { this.phoneNum = phoneNum; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Memento createMemento() { return new Memento(this.phoneNum, this.address); } public void setMemento(Memento memento) { this.phoneNum = memento.getPhoneNum(); this.address = memento.getAddress(); } } public class Memento { private String phoneNum; private String address; public Memento(String phoneNum, String address) { this.phoneNum = phoneNum; this.address = address; } }测试代码
import org.junit.Test; import static org.junit.Assert.*; public class MementoTest { @Test public void testMemento(){ Buyer buyer = new Buyer("Tom", "0755-12345678", "Shenzhen"); assertEquals("the original phone number is 0755-12345678", "0755-12345678", buyer.getPhoneNum()); assertEquals("the original address is Shenzhen", "Shenzhen", buyer.getAddress()); Memento memento = buyer.createMemento(); buyer.setPhoneNum("021-88888888"); buyer.setAddress("ShangHai"); assertEquals("the phone number is changed to 021-88888888", "021-88888888", buyer.getPhoneNum()); assertEquals("the original address is changed to ShangHai", "ShangHai", buyer.getAddress()); buyer.setMemento(memento); assertEquals("the phone number is restored to 0755-12345678", "0755-12345678", buyer.getPhoneNum()); assertEquals("the original address is restored to Shenzhen", "Shenzhen", buyer.getAddress()); } }