Patterns 1 Intro
Patterns 1 Intro
Patterns
David Talby
This Lecture
■ What is it all about?
■ Abstract Factory
■ Composite
■ Strategy
Introduction
■ O-O Design is Hard
■ Errors are expensive
■ Reuse experts’ designs
class WidgetFactory {
Button* makeButton(args) = 0;
Window* makeWindow(args) = 0;
// other widgets…
}
The Solution II
■ Define a concrete factory for each
of the families:
class WinWidgetFactory {
Button* makeButton(args) {
return new WinButton(args);
}
Window* makeWindow(args) {
return new WinWindow(args);
}
}
The Solution III
■ Select once which family to use:
WidgetFactory* wf =
new WinWidgetFactory();
■ When creating objects in the code,
don’t use ‘new’ but call:
Button* b = wf->makeButton(args);
■ Switch families - once in the code!
■ Add a family - one new factory, no
effect on existing code!
The Big (UML)
Picture
The Fine Print
■ The factory doesn’t have to be
abstract, if we expect a remote
possibility of having another family
■ Usually one factory per application,
a perfect example of a singleton
■ Not easy to extend the abstract
factory’s interface
Known Uses
■ Different operating systems
(could be Button, could be File)
■ Different look-and-feel standards
■ Different communication protocols
Pattern of
Patterns
■ Encapsulate the varying aspect
■ Interfaces
■ Single Inheritance
■ Root has add(), remove() methods
The Fine Print
■ Sometimes useful to let objects
hold a pointer to their parent
■ A composite may cache data about
its children (count is an example)
■ Make composites responsible for
deleting their children
■ Beware of circles in the graph!
■ Any data structure to hold children
will do (list, array, hashtable, etc.)
Known Uses
■ In almost all O-O systems
■ Document editing programs
■ GUI (a form is a composite widget)
■ Compiler parse trees (a function is
composed of simpler statements or
function calls, same for modules)
■ Financial assets can be simple
(stocks, options) or a composite
portfolio
Pattern of
Patterns
■ Encapsulate the varying aspect
■ Interfaces