L28 MoreDesignPatterns
L28 MoreDesignPatterns
• Factory method
• Adapter
More Design Patterns • Observer
• Composite
CS 3331
Fall 2006
1
Factory Method Outline
To define an interface for creating an object, but let Factory method
subclasses to decide which class to instantiate.
• Adapter
Product
AbstractClass
factoryMethod()
• Observer
operation() p = factoryMethod();
• Composite
ConcreteClass
ConcreteProduct factoryMethod() return new ConcreteProduct();
Adapter
2
A Closer Look at JButton Static Structure
How the button events (e.g., clicking) are
handled?
listeners 0..*
JButton ActionListener
addActionListener() actionPerformed()
JButton button = new JButton(“Ok”);
removeActionListener()
button.addActionListener(new OkButtonListener());
fireActionPerformed()
…
e : ActionEvent
Observer
<<create>>
• Composite
fireActionPerformed(e)
actionPerformed(e)
getSource()
3
AWT Components Bouncing Multiple Balls
Product
Client AbstractFactory
makeProduct() <<create>>
PolarFactory PolarComplex
makeComplex()
create
ConcreteFactory ConcreteProuct <<create>>
RectangularFactory RectangularComplex
makeProduct()
makeComplex()
4
Template Methods Template Methods (Cont.)
• Intent • Terminology
– To define a skeleton algorithm by – Hook methods: placeholders for the
deferring some steps to subclasses behaviour to be implemented by
– To allow the subclasses to redefine subclasses
certain steps
– Template methods: methods containing
AbstractClass
… hook methods
hookMethod1()
templateMethod() … – Hot spots: changeable behaviours of
hookMethod1() hookMethod2()
hookMethod2() … generic classes represented by hook
methods
ConcreteClass – Frozen spots: fixed behaviours of generic
hookMethod1() classes represented by template methods
hookMethod2()
More Example
• Generic function plotter
– To plot arbitrary single-variable functions
on a two-dimensional space
Applet Plotter
func()
paint() …
plotFunction() func()
plotCoordinates() …
PlotSine PlotCosine
func() func()