JaiswalTraining

Get the online training



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com




Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven







Memento pattern
  • The memento pattern is a software design pattern that provides the ability to restore an object to
    its previous state (undo via rollback).
  • The memento pattern is used by two objects: the originator and a caretaker.
  • The originator is some object that has an internal state.
  • The caretaker is going to do something to the
    originator, but wants to be able to undo the change.
  • The caretaker first asks the originator for a memento object. Then it does whatever operation (or sequence of operations) it was going to do.
Purpose

  • Define an object that encapsulates how a set of objects interact.
  • Mediator promotes loose coupling by keeping objects from referring to each other
    explicitly, and it lets you vary their interaction independently.
Applications
  • A set of objects communicate in well-defined but complex ways. The resulting interdependencies are unstructured and difficult to understand.
  • Rreusing an object is difficult because it refers to and communicates with many other objects.
  • A behavior that's distributed between several classes should be customizable without a lot of
    subclassing...
Examples of Memento Pattern

  • The Memento captures and externalizes an object's internal state so that the
    object can later be restored to that state. 
  • This pattern is common among do-ityourself mechanics repairing drum brakes on their cars.

Example:

ContactType.java
package com.model;

public interface ContactType {

}

AddressBook.java
package com.model;

import java.util.ArrayList;

public class AddressBook {
  private ArrayList contacts = new ArrayList();

  public Object getMemento() {
    return new AddressBookMemento(contacts);
  }

  /*public void setMemento(Object object) {
    if (object instanceof AddressBookMemento) {
      AddressBookMemento memento =
(AddressBookMemento) object;

      contacts = memento.state;
    }
  }
*/
  

  public AddressBook() {
  }

  public AddressBook(ArrayList newContacts) {
    contacts = newContacts;
  }

  public void addContact(Contact contact) {
    if (!contacts.contains(contact)) {
      contacts.add(contact);
    }
  }

  public void removeContact(Contact contact) {
    contacts.remove(contact);
  }

  public void removeAllContacts() {
    contacts = new ArrayList();
  }

  public ArrayList getContacts() {
    return contacts;
  }

  public String toString() {
    return contacts.toString();
  }
}

Address.java
package com.model;
public class Address implements
 
ContactType{
  private String type;

  private String description;

  private String street;

  private String city;

  private String state;

  private String zipCode;

  public Address() {
  }

  public Address(String newDescription,
 String newStreet, String newCity,

      String newState, String newZipCode) {
    description = newDescription;
    street = newStreet;
    city = newCity;
    state = newState;
    zipCode = newZipCode;
  }

  public String getType() {
    return type;
  }

  public String getDescription() {
    return description;
  }

  public String getStreet() {
    return street;
  }

  public String getCity() {
    return city;
  }

  public String getState() {
    return state;
  }

  public String getZipCode() {
    return zipCode;
  }

  public void setType(String newType) {
    type = newType;
  }

  public void setDescription(String newDescription) {
    description = newDescription;
  }

  public void setStreet(String newStreet) {
    street = newStreet;
  }

  public void setCity(String newCity) {
    city = newCity;
  }

  public void setState(String newState) {
    state = newState;
  }

  public void setZipCode(String newZip) {
    zipCode = newZip;
  }

  public String toString() {
    return street + " "  + city + " "" "+ state + " "
        + zipCode + " ";
  }
}

AddressBookMemento.java
package com.model;

import java.util.ArrayList;

class AddressBookMemento {
    private ArrayList<ContactType> state;

    AddressBookMemento(ArrayList
<ContactType> contacts
) {
      this.state = contacts;
    }
  }

Contact.java
package com.model;
public class Contact implements ContactType{
  private String firstName;

  private String lastName;

  private String title;

  private String organization;

  private Address address;

  public Contact() {
  }

  public Contact(String newFirstName,
 String newLastName,

      String newTitle, String newOrganization,
 Address newAddress
) {
    firstName = newFirstName;
    lastName = newLastName;
    title = newTitle;
    organization = newOrganization;
    address = newAddress;
  }

  public String getFirstName() {
    return firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public String getTitle() {
    return title;
  }

  public String getOrganization() {
    return organization;
  }

  public Address getAddress() {
    return address;
  }

  public void setFirstName(String newFirstName) {
    firstName = newFirstName;
  }

  public void setLastName(String newLastName) {
    lastName = newLastName;
  }

  public void setTitle(String newTitle) {
    title = newTitle;
  }

  public void setOrganization(String newOrganization) {
    organization = newOrganization;
  }

  public void setAddress(Address newAddress) {
    address = newAddress;
  }

  public String toString() {
    return firstName + " " + lastName;
  }
}


Test.java
package com.test;

import com.model.AddressBook;
import com.model.Address;
import com.model.Contact;

public class Test {
  public static void main(String[] arguments) {
     
      AddressBook book = new AddressBook();

      System.out.println("Adding Contact entries for
 the AddressBook"
);
      book.addContact(new Contact("Peter""Taggart""Commander",
          "NSEA Protector"new Address()));
      book.addContact(new Contact("Tawny""Madison""Lieutenant",
          "NSEA Protector"new Address()));
      book.addContact(new Contact("Dr.""Lazarus""Dr.",
          "NSEA Protector"new Address()));
      book.addContact(new Contact("Tech Sargent""Chen",
"Tech Sargent",
          "NSEA Protector"new Address()));

      System.out.println("Contacts added. Current Contact list:");
      System.out.println(book);
      System.out.println();

      System.out.println("Creating a Memento for the address
book"
);
      Object memento = book.getMemento();
      System.out
          .println("Now that a Memento exists, it can be used
to restore"
);
      System.out
          .println(" the state of this AddressBook object,
or to set the"
);
      System.out.println(" state of a new AddressBook.");
      System.out.println();

      System.out.println("Creating new entries for the
 AddressBook"
);
      book.removeAllContacts();
      book.addContact(new Contact("Jason""Nesmith""",
          "Actor's Guild"new Address()));
      book.addContact(new Contact("Gwen""DeMarco""",
"Actor's Guild",
          new Address()));
      book.addContact(new Contact("Alexander""Dane""",
          "Actor's Guild"new Address()));
      book.addContact(new Contact("Fred""Kwan""",
"Actor's Guild",
          new Address()));

      System.out.println("New Contacts added. Current
Contact list:"
);
      System.out.println(book);
      System.out.println();
      System.out
          .println("Using the Memento object to restore
the AddressBook"
);
      System.out.println(" to its original state.");
      //book.setMemento(memento);
      System.out.println("AddressBook restored. Current
 Contact list:"
);
      System.out.println(book);

    }
}

Output:-


Download Zip code

Example:-

Caretaker.java
package com.model;

import java.util.ArrayList;

public class Caretaker {
     private ArrayList<Memento> savedStates =
 
new ArrayList<Memento>();

     public void addMemento(Memento m) {
 
savedStates.add(m)}
     public Memento getMemento(int index) {
 
return savedStates.get(index)}
  }   

Originator.java
package com.model;

public class Originator {
     private String state;
   
     public void set(String state) { 
         System.out.println("Originator: Setting
state to "
+state);
         this.state = state; 
     }

     public Memento saveToMemento() { 
         System.out.println("Originator: Saving to Memento.");
         return new Memento(state)
     }
     public void restoreFromMemento(Memento m) {
         state = m.getSavedState()
         System.out.println("Originator: State
 after restoring from Memento: "
+state);
     }
  }   

Memento.java
package com.model;
 
public class Memento {
   private String state;

   public Memento(String stateToSave) {
state = stateToSave; }
   public String getSavedState() { return state; }
}

MementoExample.java
package com.test;


import com.model.*;
 
class MementoExample {
   public static void main(String[] args) {
       Caretaker caretaker = new Caretaker();

       Originator originator = new Originator();
       originator.set("State1");
       originator.set("State2");
       caretaker.addMementooriginator.saveToMemento() );
       originator.set("State3");
       caretaker.addMementooriginator.saveToMemento() );
       originator.set("State4");

       originator.restoreFromMementocaretaker.getMemento(1) );
   }
}

Output:-


Download Zip code


Example:-

Calculator.java
package com.model;

public interface Calculator {

  // Create Memento 
  public PreviousCalculationToCareTaker
backupLastCalculation
();
  
  // setMemento
  public void restorePreviousCalculation
(PreviousCalculationToCareTaker memento);
  
  // Actual Services Provided by the originator 
  public int getCalculationResult();
  public void setFirstNumber(int firstNumber);
  public void setSecondNumber(int secondNumber);
}

CalculatorImp.java
package com.model;

public class CalculatorImp
implements Calculator {

  private int firstNumber;
  private int secondNumber;

  
  public PreviousCalculationToCareTaker backupLastCalculation() {

    // create a memento object used for
 restoring two numbers

    return new PreviousCalculationImp
(firstNumber,secondNumber);
  }

  
  public int getCalculationResult() {

    // result is adding two numbers
    return firstNumber + secondNumber;
  }


  public void restorePreviousCalculation(
PreviousCalculationToCareTaker memento) {

    this.firstNumber = ((PreviousCalculationToOriginator)
memento).getFirstNumber();
    this.secondNumber = ((PreviousCalculationToOriginator)
memento).getSecondNumber();
  }


  public void setFirstNumber(int firstNumber) {

    this.firstNumber =  firstNumber;
  }


  public void setSecondNumber(int secondNumber) {

    this.secondNumber = secondNumber;
  }
}

PreviousCalculationImp.java
package com.model;

public class PreviousCalculationImp
implements PreviousCalculationToCareTaker,
PreviousCalculationToOriginator {

private int firstNumber;
private int secondNumber;

public PreviousCalculationImp(int
firstNumber, int secondNumber) {

this.firstNumber =  firstNumber;
this.secondNumber = secondNumber;
}


public int getFirstNumber() {

return firstNumber;
}


public int getSecondNumber() {

return secondNumber;
}
}


PreviousCalculationToCareTaker.java
package com.model;

public interface PreviousCalculationToCareTaker {

}

PreviousCalculationToOriginator.java
package com.model;

public interface PreviousCalculationToOriginator {
  public int getFirstNumber();
  public int getSecondNumber();  
}

CalculatorDriver.java
package com.test;

import com.model.Calculator;
import com.model.CalculatorImp;
import com.model.PreviousCalculationToCareTaker;

public class CalculatorDriver {

  public static void main(String[] args) {

    // program starts 
    Calculator calculator = new CalculatorImp();
    
    // assume user enters two numbers
    calculator.setFirstNumber(10);
    calculator.setSecondNumber(100);
    
    // find result
    System.out.println(calculator.getCalculationResult());
    
    // Store result of this calculation in case of error
    PreviousCalculationToCareTaker memento =
 calculator.backupLastCalculation
();
    
    // user enters a number
    calculator.setFirstNumber(17);
    
    // user enters a wrong second number and
calculates result

    calculator.setSecondNumber(-290);
    
    // calculate result
    System.out.println(calculator.getCalculationResult());
    
    // user hits CTRL + Z to undo last operation and
see last result

    calculator.restorePreviousCalculation(memento);
    
    // result restored 
    System.out.println(calculator.getCalculationResult());  
  }
}

Output:-


Download Zip code