Slide 1
Design Patterns
Slides adapted from various sources
Slide 2
Outline
• Introduction• An example: the Observer pattern• History and definition of design patterns• Design pattern names and categories• Other Patterns: Facade, Singleton, Composite,
Adapter, Bridge• Pattern description Templates• Summary & Benefits
Slide 3
Software Design – bridging the gap between requirements & Implementation
• What is software design?– Expressing a solution to a problem in programming
language independent terms – creating a blueprint for implementation.
3
Requirements Analysis
Software Design
Implementation
TestingDeploymentEvolution
Systems Engineering
Slide 4
Design challenges• Designing software for reuse is hard; one must find:
– a good problem decomposition, and the right software abstractions– a design with flexibility, modularity and elegance
• Designs often emerge from an iterative process (trials and many errors)
• Successful designs do exist– two designs are almost never identical– they exhibit some recurring characteristics
• The engineering perspective: can designs be described, codified or standardized?– this would short circuit the trial and error phase– produce "better" software faster
Slide 5
What patterns have you seen in this class?
Slide 6
The Model-view-controller architecture
• Separates the application object (model) from• The way it is presented to the user (view), from • The way in which the user controls it (controller).
6
User Interface or Observer
FunctionalityData or Subject
Model
View
Controller
change
change
notifies
query
Slide 7
Client-Server Architectural Pattern
A
K
TServer
Client
Client
invocation
result
Serverinvocation
result
Process:Key:
Computer:
Slide 8
The seven layers of architecture*
Global architecture
Enterprise architecture
System architecture
Application architecture
Macro-architecture
Micro-architecture
Objects
* Mowbray and Malveau
ORB
OO architecture
Frameworks
Subsystem
Design patterns
OO programming
Slide 9
Goals of Design Standardization• Codify good design
– Distil and disseminate experience– Aid to novices and experts alike– Abstract how to think about design
• Give design structures explicit names– Common vocabulary– Reduced complexity– Greater expressiveness
• Capture and preserve design information– Articulate design decisions succinctly– Improve documentation
• Enhance important non-functional properties– Changeability– Reliability – Testability– Etc.
© E
. Gam
ma,
R. H
elm
, R. J
ohns
on, J
. Vlis
side
s an
d A
ddis
on-W
esle
y
Slide 10
How patterns arise
ProblemProblem
Context
SolutionSolution
Benefits
Related Patterns
Consequences
Forces
Slide 11
Definition & Purpose
• A recurring solution to a common software problem in a context.
• A design pattern captures design expertise –patterns are not created from thin air, but abstracted from existing design examples
• Using design patterns is reuse of design expertise• Studying design patterns is a way of studying how
the “experts” do design• Design patterns provide a vocabulary for talking
about design
Slide 12
Is this a pattern?
A=10%B=40%C=30%D=20%
Data, Model or Subject
A
BC
D
A DCB
Relative Percentages
Y 10 40 30 20
X 15 35 35 15
Z 10 40 30 20
A B C D
Change notification
Requests, modifications
Observer
Slide 13
Observer Pattern
Subject
attach (Observer)
detach (Observer)
Notify ()
Observer
Update()
Concrete Observer
Update()
observerState
Concrete Subject
GetState()
SetState()
subjectState
observers
subject
For all x in observers{ x Update(); }
observerState= subject getState();
Slide 14
Class collaboration in Observer
:ConcreteSubject a:ConcreteObserver b:ConcreteObserver
GetState()
Notify()
Update()
SetState()
GetState()
Update()
Slide 15
Code Example: An Observerpublic interface IObserver {
void update(String state); }
public class Observer1 implements IObserver {private String state;public String getState() {
return state;}public void setState(String state) {
this.state = state;}
public void update(String state) {
setState(state);System.out.println("Observer1 has received update signal with new state: " + getState());
}}
Slide 16
Code Example: A Second Observer public class Observer2 implements IObserver {
private String state;public String getState() {
return state;}
public void setState(String state) {
this.state = state;}
public void update(String state) {
setState(state);System.out.println("Observer2 has received update signal with new state: " + getState());
}}
Slide 17
Code Example: The Subjectpublic class LogSubject {
private List<IObserver> observerList = new ArrayList<IObserver>();private String state;
public String getState() { return state; } public void attach(IObserver observer) {
observerList.add(observer);}
public void detach(IObserver observer) {observerList.remove(observer);
} public void setState(String state) {
this.state = state;notify();
} private void notify() {
for (IObserver item: observerList) {item.update(getState());
}} }
Slide 18
Code Example: The main Programpublic class Client {
public static void main(String[] args) {LogSubject subject = new LogSubject();IObserver ob = new Observer();IObserver ob1 = new Observer1();IObserver ob2 = new Observer2();subject.attach(ob);subject.attach(ob1);subject.attach(ob2);subject.setState("state1");subject.setState("state2");subject.detach(ob1);subject.setState("state3");
}}
Slide 19CS 406: Design Patterns 19
Observer Pattern: Observer codeclass Subject;
class observer {public:
virtual ~observer;
protected:
virtual void Update (Subject* theChangedSubject)=0;
observer ();
Note the support for multiple subjects.};
Abstract class definingthe Observer interface.
Slide 20CS 406: Design Patterns
20
Observer Pattern: Subject Code [1]
class Subject {
public:
virtual ~Subject;
protected:
Subject ();
virtual void Attach (observer*);
virtual void Detach (observer*) ;
virtual void Notify();
private:
List <Observer*> *_observers;
};
Abstract class definingthe Subject interface.
Slide 21CS 406: Design Patterns 21
Observer Pattern: Subject Code [2]
void Subject :: Attach (Observer* o){
_observers -> Append(o);}
void Subject :: Detach (Observer* o){
_observers -> Remove(o);
}
void Subject :: Notify (){
ListIterator<Observer*> iter(_observers);
}
for ( iter.First(); !iter.IsDone(); iter.Next()) {
iter.CurrentItem() -> Update(this);
}
Slide 22
When to use the Observer Pattern?
• When an abstraction has two aspects: one dependent on the other. Encapsulating these aspects in separate objects allows one to vary and reuse them independently.
• When an update to one object requires changing others and the number of objects to be changed is not known.
• When an object should be able to notify others without knowing who they are. Avoid tight coupling between objects.
Slide 23
Observer design pattern: example 2
notifies
notifies
notifies
BankStatementData
TextDisplay
BarGraphDisplay
PieChartDisplay
Slide 24
Observer Pattern: Consequences
• Abstract coupling between subject and observer. Subject has no knowledge of concrete observer classes.
• Support for broadcast communication. A subject need not specify the receivers; all interested objects receive the notification.
• Unexpected updates: Observers need not be concerned about when updates are to occur. They are not concerned about each other’s presence.
Slide 25
History & Definition
2525
Slide 26
Observer Pattern History
• Software context:– Most of the work originated in SmallTalk
community.– SmallTalk programming language:
• Object Oriented• Meant for rapid prototyping• Came with (what are known today as) IDE and API• IDE elements were in SmallTalk!• (Concrete) Precursor to modeling, frameworks and
patterns!
Slide 27
Patterns – MVC framework
• SmallTalk’s user interface framework– Model - refers to data model– View – refers to external views or presentation of
data.– Controller – refers to module relating reactions of
view or presentation to changes in data.
Slide 28
The Model-view-controller architecture
• Separates the application object (model) from• The way it is presented to the user (view), from • The way in which the user controls it (controller).
28
User Interface or Observer
FunctionalityData or Subject
Model
View
Controller
change
change
notifies
query
Slide 29
Observer Pattern
• Model – View paradigm can be generalized:– A view is an observer– A model is an subject that is observed.– The controller may be the communication
between model and view or may be incorporated in the view or model.
Slide 30
Pattern origins and history• Writings of architect Christopher Alexander
(coined this use of the term "pattern" ca. 1977-1979) – A Pattern Language in 1977 (253 patterns)
• Kent Beck and Ward Cunningham, Textronix, OOPSLA'87(used Alexander's "pattern" ideas for Smalltalk GUI design)
• Erich Gamma, Ph. D. thesis, 1988-1991 • Gamma, Helm, Johnson, Vlissides ("Gang of Four“ - GoF) Design Patterns: Elements of Reusable
Object-Oriented Software, 1991-1994 • James Coplien, Advanced C++ Idioms book, 1989-1991 • PLoP Conferences and books, 1994-present: http://hillside.net/plop/2006/ • Buschmann, Meunier, Rohnert, Sommerland, Stal, Pattern -Oriented
Software Architecture: A System of Patterns (“POSA book”)
Slide 31
Definition• A recurring solution to a common software
problem in a context.• Each pattern describes a problem which occurs over and over again in
our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice [Alexander].
• … the abstraction from a concrete form which keeps recurring in specific non-arbitrary contexts [Riehle].
• …both a thing and the instructions for making the thing [Coplien]• ...a literary format for capturing the wisdom and experience of expert
designers, and communicating it to novices.
Slide 32
Design Pattern
Names & Categories
3232
Slide 33
Purpose
Creational Structural Behavioral
Class· Factory Method · Adapter · Interperter
ScopeObject
· AbstractFactory
· Builder· Prototype· Singleton
· Adapter· Bridge· Composite· Decorator· Facade· Flyweight· Proxy
· Chain of Responsibility· Command· Iterator· Mediator· Momento· Observer· State· Strategy· Vistor• Creational patterns
– Abstracts the instantiation process– Dynamically create objects so that they don’t have to be instantiated
directly.– Help make a system independent of how objects are represented, created
and composed.
• Structural patterns– Concerns how groups of objects are composed into larger structures• Behavioral patterns– Defines communication among objects in a given system– Provides better control of flow in a complex application
Design pattern catalog - GoF
Slide 34
Types of software patterns• Design patterns (software design)
[Buschmann-POSA]– architectural (systems design) – Susbsystem design (micro-architectures) [Gamma-GoF]
• Analysis patterns (recurring & reusable analysis models) [Flower]• Organization patterns (structure of organizations/projects) • Process patterns (software process design) • Other patterns…
Slide 35
Other Design Patterns
3535
Slide 36
Facade Pattern: Problem
AC
B Client Classes
s1
s5
s3s2
s4 Subsystem classes
Need to communicatewith
Slide 37
Facade Pattern: Solution
AC
B Client Classes
S1
S5
S3S2
S4 Subsystem classes
Facade
Slide 38
Facade• Provide unified interface to interfaces within a subsystem• Shield clients from subsystem components• Promote weak coupling between client and subsystem components
FacadeClient
Slide 39
Facade Pattern: Why and What?
• Need to provide a simple interface to many, often small, classes. But not necessarily to ALL classes of the subsystem.
• Facade provides a simple default view good enough for most clients.
• Facade decouples a subsystem from its clients.
• Subsystems often get complex as they evolve.
• A facade can be a single entry point to each subsystem level. This allows layering.
Slide 40
Facade Pattern: Benefits
• Promotes weak coupling between subsystem and its clients.
• Helps in layering the system. Helps eliminate circular dependencies.
• Shields clients from subsystem classes; reduces the number of objects that clients deal with.– Clients do not have direct access to subsystem classes.
Slide 41
Singleton Structure
Singleton
static Instance()
SingletonOp()
GetSingletonData()
static uniqueInstance
singletonDatareturn uniqueinstance
Slide 42
Composite• Construct part-whole hierarchy• Simplify client interface to leaves/composites• Easier to add new kinds of components
ComponentOperation()Add(Component)Remove(Component)
CompositeOperation()Add(Component)Remove(Component)
LeafOperation()
Client
children
0..*
For all c in children c.Operation();
Slide 43
Composite (2)• Example: figures in a structured graphics toolkit
Figurepaint()translate()getBounds()
CompositeFigurepaint()addFigure(Figure))removeFigure(Figure))
BasicFigurepaint()
Viewchildren
0..*
For all c in children c.paint();
LabelFigurepaint()
0..*
Controller
parent
Slide 44
Adapter pattern
• Delegation is used to bind an Adapter and an Adaptee• Interface inheritance is use to specify the interface of the Adapter class.• Target and Adaptee (usually called legacy system) pre-exist the Adapter.• Target may be realized as an interface in Java.
ClientClientInterface
Request()
LegacyClass
ExistingRequest()
Adapter
Request()
adaptee
Slide 45
Adapter Pattern• “Convert the interface of a class into another interface clients expect.”• The adapter pattern lets classes work together that couldn’t otherwise
because of incompatible interfaces• Used to provide a new interface to existing legacy components (Interface
engineering, reengineering).• Also known as a wrapper• Two adapter patterns:
– Class adapter: • Uses multiple inheritance to adapt one interface to another
– Object adapter: • Uses single inheritance and delegation
Slide 46
Bridge Pattern
• Use a bridge to “decouple an abstraction from its implementation so that the two can vary independently”. (From [Gamma et al 1995])
• Also know as a Handle/Body pattern.• Allows different implementations of an interface to
be decided upon dynamically.• The bridge pattern is used to provide multiple
implementations under the same interface.– Examples: Interface to a component that is incomplete, not
yet known or unavailable during testing
Slide 47
Bridge Pattern
Abstraction
Operation()
imp
Client
Imp->OperationImp();
Concrete Implementor B
OperationImpl()
Refined Abstraction 2
Operation()
Refined Abstraction 1
Operation()
Concrete Implementor A
OperationImpl()
Implementor
OperationImpl()
Slide 48
Adapter vs Bridge• Similarities:
– Both are used to hide the details of the underlying implementation.• Difference:
– The adapter pattern is geared towards making unrelated components work together
• Applied to systems after they’re designed (reengineering, interface engineering).
– A bridge, on the other hand, is used up-front in a design to let abstractions and implementations vary independently.
• Green field engineering of an “extensible system” • New “beasts” can be added to the “object zoo”, even if these are
not known at analysis or system design time.
Slide 49
Pattern Description
Template
4949
Slide 50
Pattern Description: GoF form
Pattern name and classification Intent
what does pattern do / when the solution works Also known as
other known names of pattern (if any)Motivation
the design problem / how class and object structures solve the problemApplicability
situations where pattern can be appliedStructure
a graphical representation of classes in the patternParticipants
the classes/objects participating and their responsibilitiesCollaborations
of the participants to carry out responsibilities
Slide 51
Pattern Description: GoF form
Consequences trade-offs, concerns
Implementation hints, techniques
Sample code code fragment showing possible implementation
Known uses patterns found in real systems
Related patterns
closely related patterns
Slide 52
Pattern Description: Alexandrian form
Namemeaningful name
Problemthe statement of the problem
Contexta situation giving rise to a problem
Forcesa description of relevant forces and constraints
Solution proven solution to the problem
Examples sample applications of the pattern
Resulting context (force resolution)the state of the system after pattern has been applied
Slide 53
Pattern Description: Alexandrian form
Rationale explanation of steps or rules in the pattern
Related patterns static and dynamic relationship
Known useoccurrence of the pattern and its application within existing system
Slide 54
Summary
5454
Slide 55
Benefits of using patterns• Patterns are a common design vocabulary
– allows engineers to abstract a problem and talk about that abstraction in isolation from its implementation
– embodies a culture; domain specific patterns increase design speed• Patterns capture design expertise and allow that expertise to be
communicated– promotes design reuse and avoid mistakes
• Improve documentation (less is needed) and understandability (patterns are described well once)
• Using design patterns is reuse of design expertise• Studying design patterns is a way of studying how the “experts” do design• Patterns do not provide exact solutions, solve all design problems or only
apply to OO systems.
Slide 56
Patterns vs “Design”
• Patterns are design– But: patterns transcend the “identify classes
and associations” approach to design– Instead: learn to recognize patterns in the
problem space and translate to the solution• Patterns can capture OO design principles
within a specific domain• Patterns provide structure to “design”
Slide 57
Patterns vs Frameworks
• Patterns are lower-level than frameworks• Frameworks typically employ many patterns:
– Factory– Strategy– Composite– Observer
• Done well, patterns are the “plumbing” of a framework
Slide 58
Patterns vs Architecture
• Design Patterns (GoF) represent a lower level of system structure than “architecture” (cf: seven levels of A)
• Patterns can be applied to architecture:– Mowbray and Malveau– Buschmann et al– Schmidt et al
• Architectural patterns tend to be focussed on middleware. They are good at capturing:– Concurrency– Distribution– Synchronization
Slide 59
More about patterns
• A pattern describes a recurring software structure– is abstract from concrete design elements such as problem domain,
programming language– identifies classes that play a role in the solution to a problem,
describes their collaborations and responsibilities– lists implementation trade-offs– patterns are not code or designs; must be instantiated/applied
• The software engineer is required to:– evaluate trade-offs and impact of using a pattern in the system at hand– Make design and implementation decision how best to apply the
pattern, perhaps modify it slightly– Implement the pattern in code and combine it with other patterns
Slide 60
• Six ways patterns can aid MDE?• Coding patterns?
Patterns & Model-
Driven Development
60
60
Slide 61
Online resources
• Pattern FAQ• http://g.oswego.edu/dl/pd-FAQ/pd-FAQ.html
• Basic patterns• http://exciton.cs.oberlin.edu/javaresources/DesignPatt
erns/default.htm
• Patterns home page• http://hillside.net/patterns/
Slide 62
Other resources• Design Patterns – Elements of Reusable Object-Oriented
Software– Erich Gamma, et. Al, ISBN 0-201-63361-2
• Java Design Patterns– James W. Cooper, ISBN 0-201-48539-7
• Head First Design Patterns– Eric & Elisabeth Freeman (with Kathy Sierra & Bert Bates)– ISBN 0-596-00712-4
Slide 63The End
CSC550, Devon M. Simmonds, Computer Science Department, University of North Carolina Wilmington
???????????????
…CSC550 …
Q u e s t i o n s ?
Slide 64
An Example: http://en.wikipedia.org/wiki/Bridge_pattern
import java.util.*;/** "Implementor" */interface DrawingAPI { public void drawCircle(double x, double y, double radius);}
/** "ConcreteImplementor" 1/2 */class DrawingAPI1 implements DrawingAPI { public void drawCircle(double x, double y, double radius) { System.out.printf("API1.circle at %f:%f radius %f\n", x, y, radius); }}
/** "ConcreteImplementor" 2/2 */class DrawingAPI2 implements DrawingAPI { public void drawCircle(double x, double y, double radius) { System.out.printf("API2.circle at %f:%f radius %f\n", x, y, radius); }}
Slide 65
An Example …/** "Abstraction" */interface Shape { public void draw();
public void resizeByPercentage(double pct);}
/** "Refined Abstraction" */class CircleShape implements Shape { private double x, y, radius; private DrawingAPI drawingAPI; public CircleShape(double x, double y, double radius, DrawingAPI drawingAPI) { this.x = x; this.y = y; this.radius = radius; this.drawingAPI = drawingAPI; }
public void draw() { drawingAPI.drawCircle(x, y, radius); } public void resizeByPercentage(double pct) { radius *= pct; }}
Slide 66
An Example …/** "Client" */class BridgePattern { public static void main(String[] args) { Shape[] shapes = new Shape[2]; shapes[0] = new CircleShape(1, 2, 3, new DrawingAPI1()); shapes[1] = new CircleShape(5, 7, 11, new DrawingAPI2()); for (Shape shape : shapes) { shape.resizeByPercentage(2.5); shape.draw(); } }}
Slide 67
Slide 68
Motivating Example
6868
Slide 69
A Scenario
A=10%B=40%C=30%D=20%Data
A
BC
D
A DCB
Relative Percentages
Y 10 40 30 20
X 15 35 35 15
Z 10 40 30 20
A B C D
Change notification
Requests, modifications
Views
Slide 70
A Scenario
Data
A
BC
D
A DCB
Relative Percentages
Y 10 40 30 20
X 15 35 35 15
Z 10 40 30 20
A B C D
Change notificationRequests, modifications
Views
A 10B 40C 30D 20
• Need to separate presentational aspects with the data, i.e. separate views and data.
• Change in one view automatically reflected in other views. Also, change in the application data is reflected in all views.
• Defines one-to-many dependency amongst objects so that when one object changes its state, all its dependents are notified.
• Classes defining application data and presentation can be reused.
Slide 71
Is this a pattern?
A=10%B=40%C=30%D=20%
Data, Model or Subject
A
BC
D
A DCB
Relative Percentages
Y 10 40 30 20
X 15 35 35 15
Z 10 40 30 20
A B C D
Change notification
Requests, modifications
Observer