`
cywhoyi
  • 浏览: 412985 次
  • 性别: 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.

分享到:
评论

相关推荐

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

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

    36种最新设计模式整理

    Design Pattern: Simple Factory 模式 Design Pattern: Abstract Factory 模式 Design Pattern: Builder 模式 Design Pattern: Factory Method 模式 Design Pattern: Prototype 模式 Design Pattern: Singleton...

    Java.Design.Patterns.1537192353

    Java design patterns with the Simplest real world examples which are easy to understand & remember as well. Table of Contents PREFACE ABOUT DESIGN PATTERNS SINGLETON PATTERN ...MEMENTO PATTERN

    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

    design-pattern-java.pdf

    协调多个对象之间的交互——中介者模式(三) 协调多个对象之间的交互——中介者模式(四) 协调多个对象之间的交互——中介者模式(五) 备忘录模式-Memento Pattern 撤销功能的实现——备忘录模式(一) 撤销功能...

    《Java Design Patterns》高清完整英文PDF版

    Learn how to implement design patterns in Java: each pattern in Java Design Patterns is a complete implementation and the output is generated using Eclipse, making the code accessible to all....

    设计模式 design pattern

    5.6 MEMENTO(备忘录)—对象行为型 模式 188 5.7 OBSERVER(观察者)—对象行为型 模式 194 5.8 STATE(状态)—对象行为型模式 201 5.9 STRATEGY(策略)—对象行为型 模式 208 5.10 TEMPLATE METHOD(模板方法) ...

    Design Patterns Elements of Reusable Object-Oriented Software

    • What Is a Design Pattern? • Design Patterns in Smalltalk MVC • Describing Design Patterns • The Catalog of Design Patterns • Organizing the Catalog • How Design Patterns Solve Design ...

    Apress.Pro.Design.Patterns.in.Swift

    The Swift programming... The Memento Pattern Chapter 24. The Strategy Pattern Chapter 25. The Visitor Pattern Chapter 26. The Template Method Pattern Part 5 - The MVC Pattern Chapter 27. The MVC Pattern

    CoreJava-DesignPattern

    CoreJava-DesignPattern 创意设计模式 -- Abstract Factory - Done -- Builder - Done -- Factory Method -- Object Pool -- Prototype - Done -- Singleton - Done 结构设计模式 -- Adapter -- Bridge -- ...

    design patterns elements of reusable object-oriented software

    ★附录A介绍了剩下的设计模式:Bridge(桥接)、Builder(生成器)、Chainof Responsibility(责任链)、Flyweight(蝇量)、Interpreter(解释器)、Mediator(中介者)、Memento(备忘录)、Prototype(原型)、...

    Design-pattern-Adapter-Factory-Command-Memento:Java中的Adapter&Factory&Command&Memento设计模式

    设计模式-适配器-工厂-命令-备忘录Java中的Adapter&Factory&Command&Memento设计模式GoodHealth Fitness Corporation 是一家大型健身俱乐部。 它提供最先进的设备供其成员使用。 公司维护一个会员系统,用于记录会员...

    Beginning SOLID Principles and Design Patterns for ASP.NET Developers.pdf

    ■Chapter 8: Behavioral Patterns: Mediator, Memento, and Observer ■Chapter 9: Behavioral Patterns: State, Strategy, Template Method, and Visitor ■Chapter 10: Patterns of Enterprise Application ...

    designPatterns:设计模式

    design pattern 设计模式 创建型设计模式 创建型模式设计到将对象实例化,这类模式都提供了一个方法,将客户从所需要的实例化对象中解耦。 原型模式 Prototype 结构型设计模式 结构型模式可以让你把类或者对象组合到...

    精通Objective-C设计模式 源代码

    Implementation of specific pattern approaches will prove their value to any developer working in the iOS application arena. You’ll learn to master classic patterns like singleton, abstract factory, ...

    Cocoa Fundamentals Guide

    MVC as a Compound Design Pattern 163 Design Guidelines for MVC Applications 165 Model-View-Controller in Cocoa (Mac OS X) 167 Object Modeling 167 Entities 168 Attributes 168 Relationships 169 ...

    iOS-Design-Patterns:iOS设计模式集合

    MementoPattern 备忘录设计模式的完整实现 在不破坏封装的情况下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可以将该对象恢复到原先保存的状态 本人已经将创建状态与恢复状态的逻辑抽象成了...

    设计模式迷你手册.chm

    设计模式迷你手册.chm,大小仅 188 KB,图文并茂,介绍性强,每个设计模式附有 C++、C# 示例源码示例。 目录: 创建型 Factory Method Abstract Factory ... C#:factorymethod_designpattern.cs.txt

    design-patterns:设计模式

    设计模式之馋 参考资料 六大原则 (单一职责原则) 原则 替换原则(liskov替换...备忘录模式(memento pattern) 观察者模式(观察者模式) 状态模式 策略模式 模板方法模式(模板方法模式) 访问者模式(访客模式)

Global site tag (gtag.js) - Google Analytics