网站设计工作室公司,南昌seo服务,服务行业做网站,网站做seo推广方案文章目录 概念结构实例总结 概念
备忘录模式#xff1a;在不破坏封装的前提下捕获一个对象的内部状态#xff0c;并在该对象之外保存这个状态#xff0c;像这样可以在以后将对象恢复到原先保存的状态。 就好比我们下象棋#xff0c;下完之后发现走错了#xff0c;想要回退… 文章目录 概念结构实例总结 概念
备忘录模式在不破坏封装的前提下捕获一个对象的内部状态并在该对象之外保存这个状态像这样可以在以后将对象恢复到原先保存的状态。 就好比我们下象棋下完之后发现走错了想要回退到上一步这就是备忘录模式的应用。 该设计模式的拉丁文为Memento在拉丁语中为【记住】的意思到中文就改为了【备忘录】。
结构 Originator(原发器):它是一个普通的类通过创建一个备忘录来存储当前内部状态也可以用备忘录来恢复其内部状态一般将系统中需要保存内部状态的类设计为原发器。 Memento(备忘录): 备忘录用于存储原发器的内部状态根据原发器来保存哪些内部状态。备忘录的设计一般可以参考原发器的设计根据实际需要确定备忘录类中的属性除了原发器和负责人类之外备忘录对象不能直接供其他类使用。 Caretaker(负责人):它负责保存备忘录。在负责人类中可以存储一个或多个备忘录对象它只负责存储对象而不能修改对象也无须知道对象的实现细节。
实例
现在来实现一个象棋的软件通过备忘录模式可以实现“悔棋”的功能。 象棋类充当原发器
public class Chessman {private String label;private int x;private int y;public Chessman(String label, int x, int y) {this.label label;this.x x;this.y y;}public void setLabel(String label) {this.label label;}public void setX(int x) {this.x x;}public void setY(int y) {this.y y;}public String getLabel() {return (this.label);}public int getX() {return (this.x);}public int getY() {return (this.y);}public ChessmanMemento save() {return new ChessmanMemento(this.label, this.x, this.y);}public void restore(ChessmanMemento memento) {this.label memento.getLabel();this.x memento.getX();this.y memento.getY();}
}ChessmanMemento类充当象棋备忘录
public class ChessmanMemento {private String label;private int x;private int y;public ChessmanMemento(String label, int x, int y) {this.label label;this.x x;this.y y;}public void setLabel(String label) {this.label label;}public void setX(int x) {this.x x;}public void setY(int y) {this.y y;}public String getLabel() {return (this.label);}public int getX() {return (this.x);}public int getY() {return (this.y);}public ChessmanMemento save() {return new ChessmanMemento(this.label, this.x, this.y);}public void restore(ChessmanMemento memento) {this.label memento.getLabel();this.x memento.getX();this.y memento.getY();}
}MementoCaretaker类象棋备忘录管理者充当负责人
public class MementoCaretaker {private ChessmanMemento memento;public ChessmanMemento getMemento() {return memento;}public void setMemento(ChessmanMemento memento) {this.memento memento;}
}客户端
public class Client {public static void main(String[] args) {MementoCaretaker mc new MementoCaretaker();Chessman chess new Chessman(车, 1, 1);display(chess);mc.setMemento(chess.save()); //保存状态chess.setY(4);display(chess);mc.setMemento(chess.save()); //保存状态chess.setX(5);display(chess);System.out.println(******悔棋******);chess.restore(mc.getMemento()); //恢复状态display(chess);}public static void display(Chessman chess) {System.out.println(棋子 chess.getLabel() 当前位置为 第 chess.getX() 行第 chess.getY() 列。);}
}打印结果
如果想做到批量回退思路是在MementoCaretaker维护一个有序的list即可用来存放ChessmanMemento对象。
总结
【原发器】就是我们要进行备份的东西【备忘录】和【原发器】基本是一样的只不过可以把它理解为【原发器】的备份【负责人】就是客户端的入口通过它来进行备份和保存但是它关联的是【备忘录】并不是【原发器】。 当我们保存一个对象在某一时刻的全部状态或部分状态需要以后它能够恢复到先前的状态时可以考虑备忘录模式。