SOFT2201/COMP9201: Software Design and Construction 1
Memento and Prototype
Dr. Xi Wu
School of Computer Science
The University of Sydney
Page 1
Copyright warning
COMMONWEALTH OF AUSTRALIA Copyright Regulations 1969 WARNING
This material has been reproduced and communicated to you by or on behalf of the University of Sydney
pursuant to Part VB of the Copyright Act 1968 (the Act).
The material in this communication may be subject to copyright under the Act. Any further copying or communication of this material by you may be the subject of copyright protection under
the Act.
Do not remove this notice.
The University of Sydney Page 2
Agenda
– Behavioural Design Pattern – Memento
– Creational Design Pattern – Prototype
The University of Sydney
Page 3
Memento Design Pattern
Object Behavioural
The University of Sydney Page 4
Behavioural Patterns (GoF)
Pattern Name
Description
Strategy
Define a family of algorithms, encapsulate each one, and make them interchangeable (let algorithm vary independently from clients that use it)
State
Allow an object to alter its behaviour when its internal state changes. The object will appear to change to its class
Observer
Define a one-to-many dependency between objects so that when one object changes, all its dependents are notified and updated automatically
Memento
Without violating encapsulation, capture and externalise an object’s internal state so that the state can later be restored to this state
The University of Sydney Page 5
Memento Pattern
– Intent
– Capture and externalise an object’s internal state so that the object can
be restored to this state later, without violating encapsulation – Applicability
– Asnapshotof,orsomeportionof,anobject’sstatemustbesavedsothatitcan be restored to that state later, and
– Adirectinterfacetoobtainingthestatewouldexposeimplementationdetails and break the object’s encapsulation
The University of Sydney Page 6
Memento Pattern
– Intent
– Capture and externalise an object’s internal state so that the object can
be restored to this state later, without violating encapsulation
– Examples
– Save/Load
– Undo/Redo
The University of Sydney Page 7
Memento – Implementing Undo
– Consider implementing checkpoints and an undo mechanism that lets users revert operations
– Howcouldsuchbehaviourbedesigned?
– Whatinformationshouldbecaptured?
– Howandwhereshouldtheinformationbestored?
– Isthewayyouproposedtostoretheinformationagooddesign?Why?Why not?
The University of Sydney
Page 8
Memento – Implementing Undo
– State information must be stored so that objects can be restored to their previous state
– Encapsulation – objects normally encapsulate some or all of their state which makes it inaccessible to other objects and impossible to save externally
– Exposing this state would violate encapsulation; and can compromise application’s reliability and extensibility
The University of Sydney Page 9
Memento – Graphics Editor (Undo)
– A graphics editor allow users to connect and move shapes
– E.g.,connecttworectangleswithaline
– Rectanglesstayconnectedwhentheusermoveseitheroftherectangles – Theeditorensuresthatthelinestretchestomaintaintheconnection
The University of Sydney
Page 10
Memento – Graphics Editor (Undo) – Problem
– ConstraintSolver object records connections as they are made and generates mathematical equations that describe them
– ConstraintSolverusestheresultsofitscalculationtorearrangethe graphics so that they maintain the proper connections
– Howto“undo”amoveoperation?
– Storetheoriginaldistancemovedandmovetheobjectbacktoanequivalent
distance
The University of Sydney Page 11
Memento – Graphics Editor (Undo) – Problem
– Does the ConstraintSolver’s public interface suffice to allow precise reversal of its effect on other objects?
– The undo mechanism must work closely with the ConstraintSolver to re- establish the previous state
– Should avoid exposing the ContraintSolver’s internals to the undo mechanism
– Howtosolvethisproblem?
The University of Sydney Page 12
Memento – Graphics Editor (Undo) – Solution
– The undo mechanism requests a memento from the originator when it needs to checkpoint the originator’s state
– The originator initialise the memento with current state information
– Only the originator can store and retrieve information from memento – the
memento is not transparent to other objects
The University of Sydney Page 13
Memento – Graphics Editor (Undo) – Solution
1. When a user makes a move operation, the editor requests a memento from the ConstraintSolver
2. The ConstraintSolver creates and returns a memento, an instance of a class (e.g., SolverState), which contains data structures that describe the current state of the ConstraintSolver’s internal equations and variables
3. When the user undoes the move operation, the editor gives the SolverState back to the ConstraintSolver
4. The ConstraintSolver changes its internal structures to return its equations and variables to their exact previous state
The University of Sydney Page 14
Memento – Structure
The University of Sydney Page 15
Memento – Structure
ConstraintSolver
SolverState state
SolverState
The University of Sydney Page 16
Memento – Participants (1)
– Memento (SolverState)
– StoresinternalstateoftheOriginatorobject.Themementomaystoreasmuchor
as little of the originator’s internal state as necessary at its originator’s discretion
– Protectsagainstaccessbyobjectsotherthantheoriginator.Mementoshave effectively two interfaces
• Caretaker:seesanarrowinterfacetotheMemento—itcanonlypassthe memento to other objects
The University of Sydney
Page 17
• Originator:seesawideinterface,onethatletsitaccessallthedata necessary to restore itself to its previous state
Memento – Participants (2)
– Originator (ConstraintSolver)
– Createsamementocontainingasnapshotofitscurrentinternalstate – Usesthemementorestoreitsinternalstate
– Caretaker (undo mechanism)
– Responsibleforthememento’ssafekeeping
– Neveroperatesonorexaminesthecontentsofamemento
The University of Sydney
Page 18
Memento – Collaborations
The University of Sydney Page 19
Memento – Consequences (1)
– Preserve encapsulation boundaries
– Byprotectingotherobjectsfrompotentiallycomplexoriginatorinternals
– Simplifies Originator
– Originatorkeepstheversionsofinternalstatethatclientshaverequested
– Might be expensive
– Iftheoriginatormustcopylargeamountsofinformationtostoreinthememento
or,
– Ifclientsoftencreateandreturnmementostotheoriginator
The University of Sydney Page 20
Memento – Load/Save
Text document editor
‒ Wewanttosavethestatesowecanloaditagainlater
‒ TheOriginatorcontainsthestatethatrepresentsthedocumentbeingedited(and
perhaps the interface to the editing functionality.)
The University of Sydney
Page 21
Memento – Load/Save
Text document editor
‒ Wewanttosavethestatesowecanloaditagainlater
‒ TheOriginatorcontainsthestatethatrepresentsthedocumentbeingedited
‒ AMementostoresthestate,andhasaninterfacethatgivesanOriginatorfullaccess
to the state (for restoring purposes).
‒ IfaCaretakerneedstostoreastate,itaskstheOriginatorforaMemento
representing the current state, then stores it.
‒ IfaCaretakerneedstorestoreastate,itaskstheOriginatortorestorestate,and
passes it a Memento containing the state.
The University of Sydney
Page 24
Prototype Design Pattern
Object Creational
The University of Sydney Page 27
Creational Patterns (GoF)
Pattern Name
Description
Factory Method
Define an interface for creating an object, but let sub-class decide which class to instantiate (class instantiation deferred to subclasses)
Builder
Separate the construction of a complex object from its representation so that the same construction process can create different representations
Prototype
Specify the kinds of objects to create using a prototype instance, and create new objects by copying this prototype
Singleton
Ensure a class only has one instance, and provide global point of access to it
The University of Sydney Page 28
Prototype
– Intent
– Specify the kinds of objects to create using a prototypical instance, and
create new objects by copying this prototype – Applicability
– When a system should be independent of how its products are created, composed, and represented
– To avoid building a class hierarchy of factories that parallels the class hierarchy of products
– When instances of a class can have one of only a few different combinations of state
– When the classes to instantiate are specified at run-time
The University of Sydney Page 29
Prototype
– Intent
– Specify the kinds of objects to create using a prototypical instance, and
create new objects by copying this prototype – Applicability
– When a system should be independent of how its products are created, composed, and represented
– To avoid building a class hierarchy of factories that parallels the class hierarchy of products
– When instances of a class can have one of only a few different combinations of state
– When the classes to instantiate are specified at run-time
The University of Sydney Page 30
Prototype
– A simple example
public interface Entity {}
// various classes that implement Entity …
AbstractCollection
– How do you make a deep copy of your container?
The University of Sydney
Page 31
Prototype – Structure
The University of Sydney Page 32
Prototype – Participants
– Prototype
– Declaresaninterfaceforcloningitself
– ConcretePrototype
– Implements an operation for cloning itself.
– Client
– Createsanewobjectbyaskingaprototypetocloneitself
– Collaborations
– Aclientasksaprototypetocloneitself
The University of Sydney
Page 33
Prototype – Consequences (1)
– It hides the concrete product classes from the client, thereby reducing the number of names clients know about
– These patterns let a client work with application-specific classes without modification
– Each subclass of prototype must implement the clone operation
The University of Sydney
Page 34
Prototype – Consequences (1)
– It hides the concrete product classes from the client, thereby reducing the number of names clients know about
– These patterns let a client work with application-specific classes without modification
– Eachsubclassofprototypemustimplementthecloneoperation
The University of Sydney
Page 35
Prototype – Consequences (2)
1- Adding and removing products at run-time
– New concrete product class can be incorporated into a system
– Theclientcaninstallandremoveprototypesatrun-time
2- Specifying new objects by varying values
– New kinds of objects can be defined by instantiating existing classes and registering the instances as prototypes of client objects
– A client can exhibit new behaviour by delegating responsibility to the prototype – this kind of design lets users define new “classes” without programming (cloning a prototype is similar to instantiating a class)
The University of Sydney
Page 36
Prototype – Consequences (3)
1- Specifying new objects by varying structure ( ~Builder)
– Many applications build objects from parts and subparts and for convenience let you instantiate complex, user-defined structures
– Editors for circuit designs build circuits out of sub-circuits; specific sub-circuits can be used
– Similarly, sub-circuit can be added as a prototype to the palette of available circuit elements
– When the composite circuit object implements clone as a deep copy, circuits with different structures can be prototype
The University of Sydney Page 37
Prototype – Consequences (4)
4- Reduced sub-classing
– By cloning prototype instead of asking factory method to make a new object
– FactorymethodproducesahierarchyofCreatorclassesthatparalleltheclass hierarchy
The University of Sydney Page 38
Prototype – Consequences (4)
4- Reduced sub-classing
– By cloning prototype instead of asking factory method to make a new object
public class NotQuiteAFactoryMethodButSortaIs {
private MyPrototypeInterface prototype;
public NotQuiteAFactoryMethodButSortaIs( MyPrototypeInterface prototype) {
this.prototype = prototype; }
public MyPrototypeInterface create() { return prototype.clone();
} }
The University of Sydney
Page 39
Prototype – Consequences (5)
5- Configure an application with classes dynamically
An application that wants to create instances of a dynamically loaded class won’t be able to reference its constructor statically – how to do this?
– The run-time environment creates an instance of each class automatically when it’s loaded, and it registers the instance with a prototype manager
– Then the application can ask the prototype manager for instances of newly loaded classes, classes that weren’t linked with the program originally
The University of Sydney Page 40
Prototype – Implementation (1)
Using a prototype manager
– Keep a registry (prototype manager) of available prototypes when prototypes in a system can be created and destroyed dynamically
– Clients will store and retrieve prototypes from the register, but will not manage them
– Before cloning, a client will ask the register for a prototype
– Prototype manager has operations for registering a prototype under a key and unregistering it
– Clients can change or even browse the registry at run-time
The University of Sydney Page 41
Prototype – Implementation (2)
Implementing the clone operation
– Shallow copy vs deep copy
– Doescloninganobjectinturncloneitsinstancevariablesordothecloneand
original just share the variables
– Cloning with complex structures usually requires a deep copy because the clone and the original must be independent
– Ensuretheclone’scomponentareclonesoftheprototype’scomponents
The University of Sydney Page 42
Prototype – Object.clone()
Java provides a clone() method
– Is it helpful?
Creates and returns a copy of this object. The precise meaning of “copy” may depend on the class of the object. The general intent is that, for any object x, the expression:
x.clone() != x
will be true, and that the expression:
x.clone().getClass() == x.getClass()
will be true, but these are not absolute requirements. While it is typically the case that:
x.clone().equals(x)
will be true, this is not an absolute requirement.
The University of Sydney Page 44
Prototype – Object.clone()
Java provides a clone() method
– Is it helpful?
“Creates and returns a copy of this object. The precise meaning of “copy” may depend on the class of the object. The general intent is that, for any object x, the expression:
…”
Ambiguous and restrictive Deep or shallow?
Use only if you have read the api documentation, understand the limitations, and are sure the rest of the related code will behave properly.
The University of Sydney Page 45
Prototype – MyClass.copy()
Write your own clone() method
– Is it helpful?
– The definition of shallow or deep is project dependent
– Use is project dependent
– If the method is public, document its use well
The University of Sydney
Page 46
Prototype
– A simple example, and a simple solution
public interface Entity {public Entity copy();} // various classes that implement Entity
…
AbstractCollection
– How do you make a deep copy of your container?
– for(Entityentity:entities){newContainer.add(entity.copy();}
The University of Sydney
Page 51
Task for Week 10
• Submit weekly exercise on canvas before 23.59pm Sunday
• Well organize time for assignment 3
• Attend Helpdesk session if you have any questions/difficulties on implementation perspective
The University of Sydney Page 53
What are we going to learn on week 11?
• Creational Design Pattern – Singleton
• Structural Design pattern – Decorator and Façade
The University of Sydney
Page 54
References
– Craig Larman. 2004. Applying UML and Patterns: An Introduction to Object- Oriented Analysis and Design and Iterative Development (3rd Edition). Prentice Hall PTR, Upper Saddle River, NJ, USA.
– Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.
1995. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley Longman Publishing Co., Inc., Boston, MA, USA.
The University of Sydney
Page 55