2/12/15 1
1
Design Patterns
Template Method, Façade, Adapter, Observer, Command
CS361 427-22 2
Template Method
❚ Problem: Some classes have a similar algorithm, but it is a little different for each class. ❚ Solution: Define the skeleton of the algorithm as a method in a superclass, deferring some steps to subclasses.
427-22 3
Template Method
❚ A template method calls abstract methods. ❚ Subclasses provide concrete implementations
- f abstract methods.
❚ Template method in superclass calls methods in subclass ❚ Template Method separates the invariant part
- f an algorithm from the parts that vary with
each subclass
427-22 4
In Swing’s JComponent
public void paint(Graphics g) { Graphics cg = getComponentGraphics(g); Graphics co = SwingGraphics.createSwingGraphics(cg); paintComponent(co); paintBorder(co); paintChildren(co); }
427-22 5
Where do template methods come from?
❚ Two classes, each with a paint() method. ❚ All getComponentGraphics and then createSwingGraphics, but do different things with them. ❚ Some have border, some don’t. Some have children, some don’t. paintComponent(co); paintBorder(co); paintChildren(co);
427-22 6