Professional Documents
Culture Documents
Dennis Mancl
Alcatel-Lucent Bell Labs
November 28, 2007
What is a pattern?
A pattern is a solution to a
problem in a context
The problem and context
come from some domain
(software development,
project management, )
The problem and context
contain some unresolved
forces that need to be
addressed.
What is a pattern?
Patterns are used
to capture
knowledge and
experience for
example, what to
think about when
making design
choices
Not a cookbook
Each pattern
might trigger
others
This example shows that there are multiple patterns in a Cookie pattern language, but this
pattern focuses on one of the critical characteristics of good chocolate chip cookies getting
the amount of chocolate right. Personally, I always follow the Nestle recipe, which is the
recipe on the bag of Nestles toll house morsels their ratio is just about right to satisfy the
competing forces of good taste and solid cookie architecture.
Software patterns
The first Object Oriented Design
Patterns are found in the book
Design Patterns by Erich Gamma,
Richard Helm, Ralph Johnson, and John
Vlissides (known as Gang of 4 or GOF)
23 patterns: three categories (Creational,
Structural, Behavioral)
Problems:
control the construction of objects
create organized collections of objects
divide responsibilities among objects for
better encapsulation and easier
modification
The Design Patterns book first appeared in fall 1994. The book was a big hit at the OOPSLA
conference (sponsored by ACM SIGPLAN) the Addison-Wesley booth was completely sold
out of copies of the book.
Many of the other books on design patterns make reference to these 23 patterns either by
repeating them, extending them, or discussing some specializations of the patterns for certain
contexts.
Singleton Pattern
Name: Singleton
Problem: We need to restrict the creation of new objects
for a particular class: only one instance.
Context: Other objects in the design need a single point
of access to use the object.
Solution: Define a static member function within the
class that returns a pointer (or reference) to the
Singleton object. The static member function will create
the object the first time it is called. All constructors are
made private to prevent other objects from being
created.
7
Singleton is the simplest pattern in the book. It is relatively easy to implement in C++.
The access to the object is controlled: by putting the instance in the private section of the
class, any function outside of the class cant directly access the object the access must be
done through the advertised interface (the getInstance() static member function).
Note: The actual construction of the singleton object is deferred until the first time the
application tries to access it see the next page.
MySingletonClass
instance : MySingletonClass *
other attributes
+ getInstance() : MySingletonClass *
MySingletonClass()
other operations
underline means
static data member
if (instance == 0) {
instance =
new MySingletonClass();
}
return instance;
Suppose you need a Singleton in a multi-threaded context. In that case, the instance == 0 test
plus the call to the new operator in the getInstance() function is a critical section. If two
threads try to do this operation at the same time, the results are unpredictable. You *might*
wind up with two instances of the singleton object.
A solution to this problem can be found in Design Patterns Explained by Alan Shalloway and
James R. Trott.
if (instance == 0) {
lock.acquire();
if (instance == 0) {
instance = new MySingletonClass();
}
lock.release();
}
return instance;
There is some overlap between idioms and design patterns. But for the most part, idioms are
aimed at more concrete circumstances, and they tend to be written as rules:
define the copy constructor, assignment operator, and destructor for C++ classes that
manage dynamic resources (for example, classes that allocate dynamic memory
regions, open file descriptors, or open databases)
always define a virtual destructor for C++ classes that contain other virtual functions
Structural
Abstract
Factory
Adapter
Chain of
Responsibility
Observer
Builder
Bridge
Command
State
Interpreter
Strategy
Behavioral
Prototype
Decorator
Iterator
Template
Method
Singleton
Facade
Mediator
Visitor
Flyweight
Memento
Proxy
10
10
Sources of information
So, you want to learn how to use these design patterns
to make your OO designs better
New books, articles, and courses on patterns are being written every day.
If you are an ACM member (ACM is Association for Computing Machinery), you can take
free online training courses, including a introduction to Design Patterns:
http://pd.acm.org/course_slc.cfm?pre=ITDT&trk=654&crs=WT-1230-180
11
12
12
Facade Pattern
Problem: The application needs a simple interface to a
complex subsystem
the subsystem might have been written by someone else
you dont want the entire development team to go back to the
subsystem documentation with lots of questions
Context:
it is important to control the dependencies between the application and
the complex subsystem you want to reduce the effort to maintain the
system
13
Facade diagram
application
application calls
some of the Facade
class operations
Facade class
scanner
database
interface
parser
formatter
14
14
Planning a Facade
Part of the OO design process: create a simplified
model of the classes in the overall system
using CRC cards (informal technique using index cards, one
card per class)
using UML Class Diagrams
15
15
Proxy example
CORBA example
client application
Stub objects have full
public interface, but no data.
They just push a message
over to the server.
ORB (server)
CORBA
IDL stubs
IDL skeletons
Interface
Repository
Object
Implementations
network
requests
responses
Generated
by a tool
Developers
fill in details
16
In the Proxy pattern, the Proxy object doesnt necessarily have a simple way to access the
information in the class that stands behind the Proxy object: it might involve a complex
communication protocol instead of just following a pointer.
For example, CORBA implementations usually generate client-side stub classes (which are
simple Proxy classes) directly from an IDL specification of a class). The operations of these
stub classes will send messages to the real object implementations that live on a server
machine. The Object Request Broker (ORB) on the client machine knows how to parse the
messages from stub classes. The ORB will pick out the right operations from the CORBAgenerated code (the IDL skeletons and Interface Repository) and the user-constructed code
(the Object Implementations) to return the right information to the client.
Examples of non-distributed-object related Proxy objects include:
bitmap objects (creating or downloading a bitmap might be deferred until the
application knows what section of the bitmap is needed)
sparse matrix objects (you might not compute all elements of an array immediately)
16
Proxy pattern
Problem: The application needs to operate on a distant
object
Context: Need a placeholder for an object
if the actual object is far away (on another computer or on a
disk), the placeholder should be in the local address space
17
18
temp: TemperatureSensor
report_URL : string
Update
page2: TempReportWebPage
call Update()
on each page
report_URL : string
Update
page3: TempReportWebPage
report_URL : string
Update
19
Observer is useful because there is often a separation between state and behavior in certain
designs. If an objects state is changed, there may be several objects that expect to be
informed of that state change.
Note that in this case, the action to be taken on a state change of TemperatureSensor
usually belongs to the observer class (TempReportWebPage). The TemperatureSensor
class doesnt know anything about web pages TemperatureSensor only keeps a list of other
objects that depend on the state of the sensor.
(Note: In the example on this slide, the TemperatureSensor object is responsible for updating
multiple web pages. This is a common occurrence you might have a system that records
temperatures from various reporting stations, but the screens to view the data might be
interested in different subsets of the reporting stations all of the airports in a particular
state, all airports serving a metropolitan area, all airports that have more than 500 flights per
day, and so on.)
19
ConcreteSubject observers
ConcreteObserver
subjectState
1
0..* observerState
GetState()
Update()
ModifyState()
Attach(Observer)
observerState =
Detach(Observer)
subject->GetState();
Notify()
subjectState = newState;
Notify();
20
20
Observer is an abstract
interface that each
ConcreteObserver must
implement (must implement
an Update() function)
Observer objects still
register by calling the
Attach() operation on a
ConcreteSubject object
Each ConcreteObserver
object will have its Update()
operation called whenever
its ConcreteSubject
changes state
Subject
Attach(Observer)
Detach(Observer)
Notify()
observers
Observer
1
0..*
Update()
return subjectState
ConcreteObserver
observerState
Update()
observerState =
subject->GetState();
21
This is the general picture of the Observer pattern (from the Design Patterns book). It has
been generalized: the ConcreteSubject gets the notification functionality from its base
class Subject. Within the implementation of the ConcreteSubject class, there will be one or
more calls to the Subject::Notify() function whenever the Subject determines that the
Observers need to be notified.
Observer is an abstract class it defines the interface that all ConcreteObservers must
implement.
21
In the Observer Pattern, there are some objects that care about
the state changes within other objects
The ConcreteObserver::Update() function might do these things:
repaint a user interface
check for exceeding thresholds
22
22
View
A 5
Model
event proc1
event proc2
Controller
23
23
Observer implementation
Is this necessary?
No. In some cases, you might know that all observers have the same
type. Then the list might declared to contain ConcreteObserver*
pointers.
In fact, the linked list could be replaced by a fixed sized pointer table or
a dynamic sized array (std::vector in C++) especially if the set of
observers is relatively static
24
24
Analysis patterns
Analysis patterns are a set of patterns that are used in
doing the initial problem analysis:
They help answer the question what objects should I define in
my system?
Analysis Patterns are just like Design Patterns they are simple solutions to recurring
problems. Each Analysis Pattern has problem and a context, and it identifies certain common
solutions.
25
26
26
Architecture patterns
You can save a lot of design work by reusing some welltested architectures:
Patterns of Software Architecture: the first book on architecture
patterns
An example: Client-Dispatcher-Server
Problem: You are designing a video on demand service
Your customers can order different movies, and you have video
servers in the central office that can play the movies
When requests come in, the system needs to decide which
server will handle each request
There is a standard division of responsibilities in the design
27
27
Client-Dispatcher-Server example
initial
stimulus
send_request(s)
c: Customer
1: receive_request(c)
called.
This will invoke the Service (it calls the
Service::receive_request()
s: Service
1.1: sn = obtain_channel(c)
:ServiceNode
Assigner
1.1.2: add
NodeUser(c)
1.1.1*: get
Capacity_and_Load()
sn: ServiceNode
1.1.4: configure
Service()
28
28
Client-Dispatcher-Server example
This design uses the Client-Dispatcher-Server pattern:
three classes share responsibility for managing communication
the Server provides a set of services, but it initially registers itself
with the Dispatcher
the Client will invoke the services provided by one or more
Servers, but it will contact the Dispatcher each time it needs a
service (to help it find the right Server)
the Dispatcher tracks the Servers and responds to the Clients that
are trying to locate a service
29
29
Some answers:
use layers, build facades, define proxies, encapsulate data
records, and encapsulate transactions
30
30
These examples are taken from the Cheat Sheet in the back cover of the Martin Fowler
Patterns of Enterprise Application Architecture book.
31
Summary
Design Patterns: an important set of object oriented
design concepts
these patterns are useful in many applications
every pattern has a documented set of Consequences
http://hillside.net/patterns/onlinepatterncatalog.htm
http://www.martinfowler.com/articles/enterprisePatterns.html
http://java.sun.com/blueprints/corej2eepatterns
http://www.headfirstlabs.com/books/hfdp/
32
32