Hooks and Templates
An application of self-sends are plans for reuse
Damien Cassou, Stéphane Ducasse and Luc Fabresse
http://stephane.ducasse.free.fr
Remember...
- A message send leads to a choice
- A class hierarchy defines the choices
- Code can be reused and refined in subclasses
- Sending a message in a class defines a hook:
- i.e., a place where subclasses can inject variations
The Template Method
- a template method specifies a skeleton
- the skeleton has hooks, i.e., places to be customized
- hooks may or may not have a default behavior
printString Template Method
printOn: Default Hook
Default behavior:
printOn: Refinement
Reusing and extending default behavior:
printOn: Redefinition
Redefinition in False
:
printOn: Redefinition
Redefinition in Interval
:
Another Template Method: Object Copy
- copying objects is complex:
- graph of connected objects
- cycles
- each class may want a different copy strategy
- simple solution for simple cases:
copy
/postCopy
Object Copy
Default hook
postCopy: Refinement
postCopy: Deeper copy
Conclusion
- Template Method is a very common design pattern
- Sending a message defines a hook
- Sending a message increases potential reuse
/