前言:【模式总览】——————————by xingoo
模式意图
这个模式主要是想通过一个对象来记录对象的某种状态,这样有利于在其他需要的场合进行恢复。
该模式还有跟多可以扩展的地方,比如可以记录多个时间的状态,每个角色都有可以扩展的空间,完全看业务场景而定。
应用场景
1 保存对象某一时刻的状态
2 避免直接暴露接口,破坏封装性
模式结构
Originator 是备忘录的发起者,记录状态的对象
class Originator{ private String state; public Memento ceateMemento() { return new Memento(state); } public void restoreMemento(Memento memento) { this.state = memento.getState(); } public String getState(){ return this.state; } public void setState(String state){ this.state = state; System.out.println("Current state = "+this.state); } }
Memento 备忘录角色,通常用于保存某种状态
class Memento{ private String state; public Memento(String state) { this.state = state; } public String getState() { return state; } public void setState(String state) { this.state = state; } }
Caretaker 备忘录的负责人,负责在恰当的时机,进行状态的恢复
class Caretaker{ private Memento memento; public Memento retrieveMemento(){ return this.memento; } public void saveMemento(Memento memento){ this.memento = memento; } }
全部代码
package com.xingoo.test.design.memento; class Originator{ private String state; public Memento ceateMemento() { return new Memento(state); } public void restoreMemento(Memento memento) { this.state = memento.getState(); } public String getState(){ return this.state; } public void setState(String state){ this.state = state; System.out.println("Current state = "+this.state); } } class Memento{ private String state; public Memento(String state) { this.state = state; } public String getState() { return state; } public void setState(String state) { this.state = state; } } class Caretaker{ private Memento memento; public Memento retrieveMemento(){ return this.memento; } public void saveMemento(Memento memento){ this.memento = memento; } } public class Client { private static Originator o = new Originator(); private static Caretaker c = new Caretaker(); public static void main(String[] args) { o.setState("On"); //记录状态 c.saveMemento(o.ceateMemento()); //更改状态 o.setState("Off"); //更新状态 o.restoreMemento(c.retrieveMemento()); } }