备忘录
来源:互联网 发布:忘不了脑营养 知乎 编辑:程序博客网 时间:2024/05/29 11:26
备忘录(Memento)在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。
类图:
代码:
publicclass Memento {
//状态类
private Stringstate;
public Memento(String state){
this.state=state;
}
public String getState() {
returnstate;
}
publicvoid setState(String state) {
this.state = state;
}
}
publicclass Originator {
//状态使用类
private Mementomemento;
publicvoid setMemento(Memento memento){
this.memento=memento;
}
public Memento createMemento(){
returnthis.memento;
}
publicvoid changeState(String state){
this.memento.setState(state);
}
publicvoid Show(){
System.out.println("状态为:"+memento.getState());
}
}
publicclass Caretaker {
//备忘录类
private Mementomemento;
public Memento getMemento() {
returnmemento;
}
public Caretaker(Memento memento) {
this.memento =new Memento(memento.getState());
}
}
publicstaticvoid main(String[] args) {
//创建状态和状态使用对象
Memento memento=new Memento("on");
Originator originator=new Originator();
originator.setMemento(memento);
originator.Show();
//创建备忘录
Caretaker caretaker=new Caretaker(originator.createMemento());
originator.changeState("off");
originator.Show();
//回复状态
originator.setMemento(caretaker.getMemento());
originator.Show();
}
优点:可以有撤销功能。
小结:
总的来说备忘录模式就是一个撤销的功能。命令模式也是具有撤销的功能,他们的不同之处在于命令模式要在执行操作前撤销,备忘录模式可以在执行后撤销。
- 备忘录
- 备忘录
- 备忘录
- 备忘录
- 备忘录
- 备忘录
- 备忘录
- 备忘录
- 备忘录
- 备忘录
- 备忘录
- 备忘录
- 备忘录
- 备忘录
- 备忘录
- 备忘录
- 备忘录
- 备忘录
- 智慧书-永恒的处世经典格言:201-240
- 遍历QTreeWidget
- 总弹出Visual Studio实时调试器的问题
- Codeforces Round #160 (Div. 1), problem: (B) Maxim and Restaurant DP+组合数学
- Android学习(5)-Android的资源访问(二)
- 备忘录
- 背包学习小记
- 数据挖掘 重点内容
- ViewPager使用示例(二)deprecated
- 智慧书-永恒的处世经典格言:241-280
- 输出一个数字的位数P31习题 2—1
- 遇到的一些有关IT的缩写
- Linux的free用法详解
- arg min的含义