`
cywhoyi
  • 浏览: 421096 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Memento Design Pattern

 
阅读更多

Memento pattern is one of the behavioral design pattern. Memento design pattern is used when we want to save the state of an object so that we can restore later on. Memento pattern is used to implement this in such a way that the saved state data of the object is not accessible outside of the object, this protects the integrity of saved state data.

Memento pattern is implemented with two objects – Originator and Caretaker. Originator is the object whose state needs to be saved and restored and it uses aninner class to save the state of Object. The inner class is called Memento and its private, so that it can’t be accessed from other objects.

Caretaker is the helper class that is responsible for storing and restoring the Originator’s state through Memento object. Since Memento is private to Originator, Caretaker can’t access it and it’s stored as a Object within the caretaker.

One of the best real life example is the text editors where we can save it’s data anytime and use undo to restore it to previous saved state. We will implement the same feature and provide a utility where we can write and save contents to a File anytime and we can restore it to last saved state. For simplicity, I will not use any IO operations to write data into file.

Originator Class

01 package com.journaldev.design.memento;
02  
03 public class FileWriterUtil {
04  
05     private String fileName;
06     private StringBuilder content;
07  
08     public FileWriterUtil(String file){
09         this.fileName=file;
10         this.content=new StringBuilder();
11     }
12  
13     @Override
14     public String toString(){
15         return this.content.toString();
16     }
17  
18     public void write(String str){
19         content.append(str);
20     }
21  
22     public Memento save(){
23         return new Memento(this.fileName,this.content);
24     }
25  
26     public void undoToLastSave(Object obj){
27         Memento memento = (Memento) obj;
28         this.fileName= memento.fileName;
29         this.content=memento.content;
30     }
31  
32     private class Memento{
33         private String fileName;
34         private StringBuilder content;
35  
36         public Memento(String file, StringBuilder content){
37             this.fileName=file;
38             //notice the deep copy so that Memento and FileWriterUtil content variables don't refer to same object
39             this.content=new StringBuilder(content);
40         }
41     }
42 }

Notice the Memento inner class and implementation of save and undo methods. Now we can continue to implement Caretaker class.

Caretaker Class

01 package com.journaldev.design.memento;
02  
03 public class FileWriterCaretaker {
04  
05     private Object obj;
06  
07     public void save(FileWriterUtil fileWriter){
08         this.obj=fileWriter.save();
09     }
10  
11     public void undo(FileWriterUtil fileWriter){
12         fileWriter.undoToLastSave(obj);
13     }
14 }

Notice that caretaker object contains the saved state in the form of Object, so it can’t alter its data and also it has no knowledge of it’s structure.

Memento Test Class

Lets write a simple test program that will use our memento implementation.

01 package com.journaldev.design.memento;
02  
03 public class FileWriterClient {
04  
05     public static void main(String[] args) {
06  
07         FileWriterCaretaker caretaker = new FileWriterCaretaker();
08  
09         FileWriterUtil fileWriter = new FileWriterUtil("data.txt");
10         fileWriter.write("First Set of Data\n");
11         System.out.println(fileWriter+"\n\n");
12  
13         // lets save the file
14         caretaker.save(fileWriter);
15         //now write something else
16         fileWriter.write("Second Set of Data\n");
17  
18         //checking file contents
19         System.out.println(fileWriter+"\n\n");
20  
21         //lets undo to last save
22         caretaker.undo(fileWriter);
23  
24         //checking file content again
25         System.out.println(fileWriter+"\n\n");
26  
27     }
28  
29 }

Output of above program is:

1 First Set of Data
2  
3 First Set of Data
4 Second Set of Data
5  
6 First Set of Data

The pattern is simple and easy to implement, one of the thing needs to take care is that Memento class should be accessible only to the Originator object. Also in client application, we should use caretaker object for saving and restoring the originator state.

Also if Originator object has properties that are not immutable, we should use deep copy or cloning to avoid data integrity issue like I have used in above example. We can use Serialization to achieve memento pattern implementation that is more generic rather than Memento pattern where every object needs to have it’s own Memento class implementation.

分享到:
评论

相关推荐

    Design Pattern英文版

    设计模式(Design Pattern)是软件工程中的一种经验总结,它是在特定上下文中为解决常见问题而提出的一套可复用的解决方案。设计模式并不直接实现为代码,而是提供了一种在面向对象设计中如何处理常见问题的指南。...

    C++设计模式(Design Pattern)范例源代码

    23种设计模式(Design Pattern)的C++实现范例,包括下面列出的各种模式,代码包含较详细注释。另外附上“设计模式迷你手册.chm”供参考。 注:项目在 VS2008 下使用。 创建型: 抽象工厂模式(Abstract Factory) 生成...

    Head First Design Pattern

    3. 行为型设计模式:例如策略模式(Strategy)、模板方法模式(Template Method)、观察者模式(Observer)、命令模式(Command)、迭代器模式(Iterator)、访问者模式(Visitor)、备忘录模式(Memento)、状态...

    Design Pattern 简明手册

    ### Design Pattern 简明手册知识点详述 #### 一、接口型(interface)模式 **1. Adapter(适配器模式)** - **定义**:允许一个类接口与另一个不兼容的类接口协同工作。 - **分类**: - **继承型Adapter**:通过...

    designpattern.zip

    本资源"designpattern.zip"包含了对Java中23种经典设计模式的详细讲解和代码实例,对于中高级Java工程师来说,是提升开发技能的必备学习材料。 设计模式通常分为创建型、结构型和行为型三大类。创建型设计模式关注...

    Gof design pattern 中文/英文版+web+学习笔记

    17. **备忘录模式(Memento)**:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这使得以后可以恢复对象到先前的状态。 18. **状态模式(State)**:允许对象在其内部状态改变时...

    design pattern PPT

    设计模式(Design Pattern)是软件工程中用于解决软件设计问题的既定方案。设计模式并非直接的代码实现,而是一套被验证过的通用解决方案模板。它们是由经验丰富的软件开发者总结出的,在特定上下文中对常见问题的...

    Swift DesignPattern

    本资料"Swift DesignPattern"包含了一些Swift语言中的常见设计模式实例,下面我们将详细探讨这些设计模式及其在Swift中的应用。 1. **单例模式(Singleton)**:单例模式确保一个类只有一个实例,并提供全局访问点...

    Design Pattern In c#

    《Design Pattern In C#》是一本深入探讨设计模式的书籍,专为使用C#编程语言的开发者准备。设计模式是软件工程中经过实践验证的、解决常见问题的有效方法,是经验丰富的开发者的智慧结晶。这本书以英文撰写,以其...

    DesignPattern.rar

    这个"DesignPattern.rar"压缩包很可能是为了帮助应届毕业生和正在学习设计模式的开发者提供一套全面的资源。设计模式并不是一种具体的代码或库,而是经验丰富的开发者们在多年实践中总结出的通用解决方案的描述。 ...

    C++11全套设计模式-23种指针的用法(a full DesignPattern -DesignPattern.zip

    本资料包“DesignPattern - DesignPattern.zip”提供了对C++11中23种设计模式的全面讲解,特别是结合指针使用的部分,以下是对这些知识点的详细阐述: 1. **单例模式(Singleton)**:确保一个类只有一个实例,并...

    Design.Patterns.Explained.Simply

    If you have ever bought any programming books, you might have noticed that there are two types of them: books that are too short to ...Memento Null Object Observer State Strategy Template Method Visitor

    JAVA design pattern-java设计模式

    在这个名为"JAVA design pattern-java设计模式"的CHM文件中,我们可能找到了关于如何在Java开发中应用设计模式的详细信息。 设计模式通常分为三大类:创建型、结构型和行为型。创建型模式关注对象的创建,如单例...

    DesignPattern.zip

    "DesignPattern.zip"这个压缩包很可能包含了一个关于设计模式的学习资源,如代码示例、教程或者文档,其名称"DesignPattern-master"可能表明这是一个版本控制库的主分支,比如Git仓库。 设计模式分为三大类:创建型...

    Design Pattern Framework 4.0 CS

    总的来说,Design Pattern Framework 4.0 CS是一份宝贵的参考资料,它将帮助C#开发者更好地理解和应用设计模式,提升代码质量,优化系统架构,从而提高开发效率和软件的可维护性。对于学习和实践设计模式的开发者来...

    DoFactory Design Pattern Framework 3.5 C#

    总的来说,DoFactory Design Pattern Framework 3.5 C#是C#开发者学习和应用设计模式的强大工具,它将设计模式的理论知识与实际开发紧密结合,有助于提升开发者的专业技能和软件设计能力。无论是初学者还是经验丰富...

    design pattern设计模式范例

    本资料库中的"design pattern设计模式范例"提供了23种经典设计模式以及最新的范式用法,非常适合用于项目重构或作为学习设计模式的参考。 首先,我们来看23种经典的设计模式,它们通常分为三类:创建型、结构型和...

Global site tag (gtag.js) - Google Analytics