Examples: Singleton & Memento

What are they?
Memento is a behavioral Design Pattern that consists of several interacting objects:
There is a class to hold the classes (usually the Application or Applet class) which holds a single instace of an Originator object.  This Originator object's job is to calculate something dynamically.  In the example I have coded, the Origniator object has a method that calculates a running average of numbers.  The Originator object encapsulates its state into a privately-held State object.  The Originator can also create a Memento object which is a sort of "snapshot" of its internal state (an instance of a state object).  The Applet class can then return the Memento object to the Originator object at a later time when the user wishes to revert to that state.
In this orientation, the Originator obejct works best if it is a Singleton class.  That is, if there is only ever one instance of it created.  As long as its state remains separate and mutable, there need only be one instance.

Intent (an anecdotal example)
Memento is a way of encapsulating the state of an object AS an object to return later when the user wishes to go back to an earlier version.  It is what your mother wanted to do to you when you were five.  Consider:
You are a singleton object.  There is only one of you in the entire world.  Now, when you were 5, your Mother really wanted to have you give her a Memento of your internal state for safekeeping.  When you turned 13, she would want to hand you back your 5-year-old state and have you implement THAT for a while.  You were so cute who could blame her!

Consequences
Most of the consequences are good ones.  They insure good Object Oriented design and safeguard against violating encapsulation.

You Try It!
Click on "Demo Code" to pop up the applet in a new window.  You can also view the code source and documentation (which includes a nifty diagram) by clicking on their respective titles below.
 

 
Demo Code
Code Source
Documentation
Readme
Next Pattern
My Plan
In Progress
Examples
Site Info
Home