zoukankan      html  css  js  c++  java
  • 备忘录模式

     Memento模式比较适用于功能比较复杂的,但需要维护或记录属性历史的类,或者需要保存的属性只是众多属性的一小部门时,

    Originator可以根据保存的Memento信息还原到前一状态

    代码部分:

     1 /**
     2  * Originator(发起人):负责创建备忘录Memento,用来记录当前时刻它的内部状态,
     3  * 并可以使用备忘录恢复内部状态,Originator可以根据需要决定Memento存储Originator
     4  * 的哪些内部状态
     5  */
     6 public class Originator {
     7     private String state;
     8 
     9     public String getState() {
    10         return state;
    11     }
    12 
    13     public void setState(String state) {
    14         this.state = state;
    15     }
    16     
    17     /**创建备忘录,将当前需要保存的信息导入并实例化出一个Memento对象 */
    18     public Memento createMemento(){
    19         return new Memento(state);
    20     }
    21     /**
    22      * 恢复备忘录,将Memento数据导入并恢复数据
    23      */
    24     public void setMemento(Memento memento){
    25         state = memento.getState();
    26     }
    27     
    28     public void show(){
    29         System.out.println("state===="+state);
    30     }
    31 }
    Originator
     1 /**
     2  * Memento(备忘录):负责存储Originator对象的内部状态,并可防止Originator以外
     3  * 的其它对象访问备忘录Memento,备忘录有两个接口,Garetaker只能看到备忘录的窄接口,
     4  * 它只是将备忘录传递给其它对象,Originator是一个宽接口,允许它访问到先前状态所需的所有数据
     5  */
     6 public class Memento {
     7     private String state;
     8 
     9     public String getState() {
    10         return state;
    11     }
    12 
    13     public void setState(String state) {
    14         this.state = state;
    15     }
    16 
    17     public Memento(String state) {
    18         super();
    19         this.state = state;
    20     }
    21 
    22     public Memento() {
    23         super();
    24     }
    25 }
    Memento
     1 /**
     2  * Garetaker(管理者):负责保存好备忘录Memento,
     3  * 不能对备忘录内容进行操作或检查
     4  */
     5 public class Garetaker {
     6     private Memento memento;
     7 
     8     public Memento getMemento() {
     9         return memento;
    10     }
    11 
    12     public void setMemento(Memento memento) {
    13         this.memento = memento;
    14     }
    15 }
    Garetaker
     1 public class MementOTest {
     2     public static void main(String[] args) {
     3         Originator or = new Originator();
     4         or.setState("ON");
     5         or.show();
     6         
     7         Garetaker ga = new Garetaker();
     8         ga.setMemento(or.createMemento());
     9         or.setState("OFF");
    10         or.show();
    11         
    12         or.setMemento(ga.getMemento());
    13         or.show();
    14     }
    15 }
    test
  • 相关阅读:
    CSS3选择器:nth-child和:nth-of-type的差异
    H5 设计尺寸
    笔试题的各种trick
    OpenCV2.4.9 + VS2012 + win10 配置
    四种IO模型
    深信服笔试
    哈希表
    TimeOut Error :因为远程服务器关闭导致mnist数据集不能通过input_data下载下来
    Http协议对格式、请求头、方法
    GDB调试
  • 原文地址:https://www.cnblogs.com/cai170221/p/13370140.html
Copyright © 2011-2022 走看看