Welcome to Mike95.com
Home
WELCOME
ABOUT MIKE95.COM
CONTACT ME


Features
FUNNY JOKES
HUMAN FACTOR


C++
Library Source Code:
CGIPARSE
JSTRING
JVECTOR
JSTACK
JHASHTABLE


COM / ASP
MIKE95 COM SVR
- ASP STACK
- ASP QUEUE
- ASP VECTOR


Tutorials:
TEMPLATES
ALGORITHMS
DESIGN PATTERNS


Sample Work
Internet Based
TASK/BUG TRACKER


Visual C++ / MFC
FLIGHT PATH (C++)
MP3 PLAY LIST


Java
JAVA TALK
BAR GRAPH
WEB CAM


Personal
CONTACT ME
RESUME
PICTURES
TRIPS
Design Patterns
Memento Pattern
Allows you to provide storage and restoration of an object's state.

Many times you have the need to restore a state of an application to a previous state. The typical scenario is the use of the Undo button. The memento pattern allows you to store the various states during the application's life cycle and then offer the ability to restore any previous state.

To illustrate this example, lets say we have a drawing program that records the strokes of a brush. With each new stroke, the state of the application is stored to allow for the undo button to remove the last stroke applied.

To accomplish this, we will have a Factory for storing all the strokes called FactoryStrokes. This factory will ensure the state of the drawing is saved with each newly added stroke. To accomplish this, a memento will be created to include all the strokes upto and including the last stroke. Given any memento, we can restore the drawing to the same state when the memento was saved. Since the undo is sequential, we will store each of these new mementos on a stack called FactoryStrokes.

Notice as we call the AddStroke() method, we create a new memento containing all strokes from the previous memento and then add the recently added stroke last. We then save the current state by pushing the memento onto the stack.

public struct Stroke
{
	public Point beginPoint;
	public Point endPoint;
}

public class FactoryStrokes
{
	Stack _mementos;	//will store the application states
	public event EventHandler RefreshEvent;
	
	public void AddStroke( Stroke lastStroke )
	{
		ArrayList newMemento = new ArrayList();
		
		//copy over previous memento
		foreach( Stroke s in _mementos.Peek() )
			newMemento.Add( s );
		
		newMemento.Add( lastStroke );
		
		//save new memento
		_mementos.Add( newMemento );
	}
	
	public IList AllStrokes
	{
		get { return _mementos.Peek(); }
	}
	
	public void Undo()
	{
		_mementos.Pop();	//remove the last memento
		
		//notifies any dependents they should update to the new state
		if ( RefreshEvent != null )
			RefreshEvent();
	}
}

(c)2024 Mike95.com / Site Disclaimer
Site Meter