template design pattern - lpu guide · 2016. 10. 9. · template design pattern . intent •define...
TRANSCRIPT
Template design pattern
Intent
• Define the skeleton of an algorithm in an operation, deferring some steps to client subclasses.
• Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
• Base class declares algorithm 'placeholders', and derived classes implement the placeholders.
Motivation
• The component designer decides which steps of an algorithm are invariant (or standard), and which are variant (or customizable).
• The invariant steps are implemented in an abstract base class, while the variant steps are either given a default implementation, or no implementation at all.
• The variant steps represent "hooks", or "placeholders", that can, or must, be supplied by the component's client in a concrete derived class.
Structure
Participants
• AbstractClass- implements a template method defining the skeleton of an algorithm
• ConcreteClass - implements the primitive operations to carry out
subclass-specificsteps of the algorithm.
Structure
Collaborations
• ConcreteClass relies on AbstractClass to implement the invariant steps of the algorithm.
Applicability
• To implement the invariant parts of an algorithm once and leave it upto subclasses to implement the behavior that can vary.
Example
Consequences
• Template methods are a fundamental technique for code reuse.
• Template methods lead to an inverted control structure that is sometimes referred to as "the Hollywood principle," that is, "Don' t call us, we' ll call you“.• This refers to how a parent class calls the operations of a subclass and not the
other way around.
Known Uses
• Template methods are so fundamental that they can be found in almost every abstract class.
Related Patterns
• Factory Methods (121) are often called by template methods.
• Strategy (349) : Template methods use inheritance to vary part of an algorithm.