Memento | slide # 1 |
...Motivation | slide # 1 |
...Consequences/ Implementation | slide # 4 |
Mediator | slide # 5 |
...When to use the Mediator Pattern | slide # 5 |
...Issues | slide # 6 |
class Memento { private Hashtable savedState = new Hashtable(); Memento() {}; //Give some protection void setState( String stateName, Object stateValue ) { savedState.put( stateName, stateValue );} Object getState( String stateName) { return savedState.get( stateName); } Object getState( String stateName, Object defaultValue ) { if ( savedState.containsKey( stateName ) ) return savedState.get( stateName); else return defaultValue; } }
class ComplexObject { private String name; private int someData; private Vector objectAsState = new Vector(); public Memento createMemento() { Memento currentState = new Memento(); currentState.setState( "name", name ); currentState.setState( "someData", new Integer(someData) ); currentState.setState( "objectAsState", objectAsState.clone() ); return currentState; } public void restoreState( Memento oldState) { name = (String) oldState.getState( "name", name ); objectAsState = (Vector) oldState.getState( "objectAsState" ); Integer data = (Integer) oldState.getState( "someData"); someData = data.intValue(); } // Show a way to do incremental saves public Memento setName( String aName ) { Memento deltaState = saveAState( "name", name); name = aName; return deltaState; }
public void setSomeData( int value ) { someData = value; } private Memento saveAState( String stateName, Object stateValue ) { Memento currentState = new Memento(); currentState.setState( stateName, stateValue ); return currentState; } }
Let originator have access to all set/get/state of Memento
Others let hold Memento's and destroy
C++ has good support for Memento
When reusing an object is difficult because it refers to and communicates with many other objects
When a behavior that's distributed between several classes
should be customizable without a lot of subclassing
class DialogDirector { private Button ok; private Button cancel; private ListBox courses; public void ListBoxItemSelected() { blah} public void ListBoxScrolled() { blah } etc. }
class DialogDirector { private Button ok; private Button cancel; private ListBox courses; public void widgetChanged( Object changedWidget) { if ( changedWidget == ok ) blah else if ( changedWidget == cancel ) more blah else if ( changedWidget == courses ) even more blah } }3) Generic change method overloaded
class DialogDirector { private Button ok; private Button cancel; private ListBox courses; public void widgetChanged( Button changedWidget) { if ( changedWidget == ok ) blah else if ( changedWidget == cancel ) more blah } public void widgetChanged( ListBox changedWidget) { now find out how it changed and respond properly } }