需求:使用clone方式实现备忘录模式
发起人角色
public class Originator implements Cloneable { //内部状态 private String state = ""; public String getState() { return state; } public void setState(String state) { this.state = state; } //创建一个备忘录 public Originator createMemento() { return this.clone(); } //恢复一个备忘录 public void restoreMemento(Originator _originator) { this.setState(_originator.getState()); } //克隆当前对象 @Override protected Originator clone() { try { return (Originator) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return null; } }
备忘录管理员角色
public class Caretaker { //发起人对象 private Originator originator; public Originator getOriginator() { return originator; } public void setOriginator(Originator originator) { this.originator = originator; } }
上面两项合并
public class Originator implements Cloneable { private Originator backup; //内部状态 private String state = ""; public String getState() { return state; } public void setState(String state) { this.state = state; } //创建一个备忘录 public void createMemento() { this.backup = this.clone(); } //恢复一个备忘录 public void restoreMemento() { //在进行恢复前应该进行断言,防止空指针 this.setState(this.backup.getState()); } //克隆当前对象 @Override protected Originator clone() { try { return (Originator) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return null; } }
调用
public class Client { public static void main(String[] args) { //定义发起人 Originator originator = new Originator(); //建立初始状态 originator.setState("初始状态..."); System.out.println("初始状态是:" + originator.getState()); //建立备份 originator.createMemento(); //修改状态 originator.setState("修改后的状态..."); System.out.println("修改后状态是:" + originator.getState()); //恢复原有状态 originator.restoreMemento(); System.out.println("恢复后状态是:" + originator.getState()); } }
结果
初始状态是:初始状态...
修改后状态是:修改后的状态...
恢复后状态是:初始状态
注意:
使用Clone方式的备忘录模式,可以使用在比较简单的场景或者比较单一的场景中,尽量不要与其他的对象产生严重的耦合关系。
原文地址:https://www.cnblogs.com/anni-qianqian/p/8444083.html
时间: 2024-11-06 17:30:59