Thursday, 12 May 2016

Memento Design Pattern in Java

Without violating encapsulation, the intent of this pattern is to capture the internal state of an object so that the object can be restored to this state later.

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.


The classes and objects participating in this pattern are:
·         Memento
·         Originator
·         Caretaker

Example of memento pattern
public class Memento {
      private String state;

      public Memento(String state){
            this.state = state;

      public String getState(){
            return state;
public class FileWriterUtil {
      private String state;

      public void setState(String state){
            this.state = state;

      public String getState(){
            return state;

      public Memento saveStateToMemento(){
            return new Memento(state);

      public void getStateFromMemento(Memento Memento){
            state = Memento.getState();
import java.util.ArrayList;
import java.util.List;

public class FileCareTaker {
      private List<Memento> mementoList = new ArrayList<Memento>();

      public void add(Memento state){

      public Memento get(int index){
            return mementoList.get(index);
public class FileHandlerClient {
      public static void main(String[] args) {

            FileWriterUtil originator = new FileWriterUtil();
            FileCareTaker careTaker = new FileCareTaker();

            /*save the current state. i.e#State#2*/

            /*save the current state. i.e#State#3*/

            System.out.println("Current State: " + originator.getState());         

            System.out.println("First saved State: " + originator.getState());
            System.out.println("Second saved State: " + originator.getState());

Current State: State#4
First saved State: State#2
Second saved State: State#3

Database Transactions:
Mechanism of rolling back the transaction can be achieved by memento design pattern.

Example in Java's core libraries:
java.util.Date (the setter methods do that, Date is internally represented by a long value)

All implementations of

All implementations of javax.faces.component.StateHolder

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...