Introduction
These pages are based on several books: Gamma et al, Design Patterns: Elements of Reuse in
Object Oriented Software; Buschmann et al, A System of Patterns; Pree, Design Patterns for
Object-OrientedSoftware Development; and Coplien and Schmidt, Pattern Languages for
Program Design. This is meant to be used as a quick tutorial on design patterns.
Much more information on design patterns can be found in the Patterns Home Page, [Link]
[Link]/users/patterns/[Link] and the Portland Pattern Repository,
[Link]
What is a design pattern?
• A design pattern is to design is what a class library is to coding
• Documentation of expert software engineers' "behaviour"
• Documentation of specific reoccuring problems (and solutions)
• Abstraction of common design occurances
• Large range of granularity -- from very general design principles to language-specific
idioms
Properties of design patterns (Buschmann 1996)
• A pattern addresses a recurring design problem that arises in specific design situations,
and presents a solition to it.
• Patterns document existing, well-proven design experience.
• Patterns identify and specify abstractions that are above the level of single classes and
instances, or of components.
• Patterns provide a common vocabulary and understanding for design principles.
• Patterns are a means of documenting software architechtures.
• Patterns support the construction of software with define properties.
• Patterns help you build complex and heterogeneous software architectures.
• Patterns help you to manage software complexity.
What's in a design pattern?
• pattern name
• problem statement: where do I apply it?
• solution: elements that make up the design
• concequences
Description elements
Design Patterns (Gamma et al 1995) uses the following headings in its pattern catalogue:
• Pattern name and classification
• Intent
• Also known as
DESIGN PATTERNS CATLOG 1
• Motivation
• Applicability
• Structure
• Participants
• Collaborations
• Consequences
• Implementation
• Sample code
• Known uses
• Related patterns
Not all authors use all these headings. Context is often added by other authors (Buschmann
1996).
Patterns provide:
• A common design vocabulary
• A documentation and learning aid
• An adjunct to existing design methods
• A target for refactoring
History of Patterns
See Coplien's "History of Patterns" for a more detailed description.
Alexander
The origins of design patterns is often attributed to the achitect Christopher Alexander. In his
book The Timeless Way of Building (Alexander79 p.247), he defines patterns as:
Each pattern is a three-part rule, which expresses a relation between a certain context, a problem,
and a solution.
As an element in the world, each pattern is a relationship between a certain context, a certain
system of forces which occurs repeatedly in that context, and a certain spatial Configuration
Which allows these forces to resolve themselves.
As an element of language, a pattern is an instruction, Which shows how this spatial
configuration can be used. over and over again. to resolve the given system of forces, wherever
the context makes it relevant.
The pattern is, in short, at the same time a thing, which happens in the world, and the rule which
tells us how to create that thing. and when we must create it. It is both a process and a thing; both
a description of a thing which is alive, and a description of the process which will generate that
thing.
DESIGN PATTERNS CATLOG 2
Ward and Kent
Ward and Kent are generally crediting with applying Alexander's ideas to software design
(1987).
Gamma
Erich Gamma completed his doctoral thesis on programming patterns at the University of Zurich
in 1991, and subsequently got together with Richard Helm, Ralph Johnson, and John Vlissides to
produce the book, Design Patterns: Elements of Reusable Object-Oriented Software (Gamma et
al 1995) in 1995.
PLoP
The first PLoP (Pattern Languages of Programming) conference occurred in 1994.
Patterns in Distributed Processing
Most of the patterns listed here apply to distributed systems, but here is a list if patterns specific
to distrubuted systems:
• Buschmann et al's Broker
• Gamma et al's Proxy and Buschmann et al's Proxy (used as local proxy for remote
objects)
• Buschmann et al's Pipes and Filters
• Buschmann et al's Microkernel
• Gamma et al's Mediator
See also Douglas Schmidt's distributed patterns papers,
[Link]
DESIGN PATTERNS CATLOG 3
------------------------------------------------------------------------------------------------------------
Creational Patterns
------------------------------------------------------------------------------------------------------------
Abstract Factory
Provides an interface for creating families of related or dependent objects without specifying
their concrete classes.
Applicability
• Need to abstract from details of implementation of products
• Need to have multiple families of products
• Need to enforce families of products that must be used together
• Need to hide product implementations and just present interfaces
Consequences
• Isolates concrete classes
• Makes exchanging product families easy
• Promotes consistency among products
• Supporting new kinds (in each family) of products in difficult
Participants
• AbstractFactory : Declares an interface for operations that create abstract product
objects.
• ConcreteFactory : Implements the operations declared in the AbstractFactory to create
concrete product objects.
• Product : Defines a product object to be created by the corresponding concrete factory
and implements the AbstractProduct interface.
• Client : Uses only interfaces declared by AbstractFactory and AbstractProduct classes.
DESIGN PATTERNS CATLOG 4
Builder
Separate the construction of a complex object from its representation so that the same
construction process can create different representations.
Applicability
• Need to isolate knowledge of the creation of a complex object from its parts
• Need to allow different implementations/interfaces of an object's parts
Consequences
• Lets you vary a product's internal representation
• Isolates code for construction and representation
• Finer control over the construction process
------------------------------------------------------------------------------------------------------------
Factory Method
Define an interface for creating an object, but let subclasses decide which class to instantiate.
Factory Method lets a class defer instantiation to subclasses.
Applicability
• A class can't anticipate the class of the objects it must create
• A class wants its subclasses to specify the objects it creates
• Need to delegate responsibility to helper subclasses
DESIGN PATTERNS CATLOG 5
Consequences
• Provides hooks for subclasses
• Connects parallel class heirarchies
------------------------------------------------------------------------------------------------------------
Prototype
Specify the kinds of objects to create using a prototypical instance, and create new object by
copying this prototype.
Applicability
• Need to specify classes to instantiate at run time
• Need to avoid building parallel class hierarchies for factories and products
• When instances of a class can have only a few different combinations of state
Consequences
• Hides concrete classes from the client
• Allows adding and removing products at run-time
• Allows specifying new object "types" by varying values or structure
• Can reduce subclassing
• Dynamic configuation of an application's classes
DESIGN PATTERNS CATLOG 6
Singleton
Ensure a class only has one instance, and provide a global point of access to it.
Applicability
• Need exactly one instance of a class and a well-known access point
• Need to have the sole instance extensible by subclassing
Consequences
• Need controlled access
• Reduce name space
• Permits refinement of operations and representation
• More flexible than static class operators
------------------------------------------------------------------------------------------------------------
DESIGN PATTERNS CATLOG 7
------------------------------------------------------------------------------------------------------------
Structural
------------------------------------------------------------------------------------------------------------
Adapter
Adapter comes in two variants; one based on multiple inheritance:
and one making use of delegation:
Convert the interface of a class into another interface clients expect. Adapter lets classes work
together that couldn't otherwise because of incompatible interfaces. (See the STL container
adaptors for a good example of adapting template containers.)
Applicability
• Need to using an existing class, but its interface doesn't match
• Need to make use of incompatible classes
• (object adapter) Need to use several existing subclasses, but don't what to subclass them
all
Consequences
• Class adapter commits to the concrete Adapter class: it won't work with Adapter's
subclasses, but object adapter does.
• Class adapter introduces only one object and no ponter indirection
DESIGN PATTERNS CATLOG 8
• Object adapter requires quite a bit of work, since all of Adaptee's interface must be
duplicated.
Bridge
Decouple an abstraction from its implementation so that the two can vary independently.
(Closely related to the object form of the Adaper pattern.)
Applicability
• Need to avoid a permanent binding between an abstraction (type!) and its implementation
• Both abstractions and implementation should be extensible through subclassing
• Need to isolate changes in implementations from clients
• Need to completely (.h files) hide implementation from clients
• Need to split objects because of prolifereation of classes ("nested generalizations")
Consequences
• Decouples interface and implementation
• Improves extensibility
• Hides implementation details from clients
------------------------------------------------------------------------------------------------------------
Composite
DESIGN PATTERNS CATLOG 9
Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients
treat individual objects and composition of objects uniformly.
Applicability
• Need to represent part-whole hierarchies
• Need to be able to ignore the difference between composites and individuals.
Consequences
• Makes the client simple
• Makes it easy to add new kinds of components
• Hard to restrict components of a composite
------------------------------------------------------------------------------------------------------------
Decorator
Attach additional responsibilities to an object dynamically. Decorators provide a flexible
alternative to subclassing for extended functionality.
Applicability
DESIGN PATTERNS CATLOG 10
• Need to add responsibilities to objects dynamically and transparently.
• Need to withdraw responsibilities
• Need to support large combinations of responsibilities without a class explosion.
Consequences
• More flexible than static inheritance
• Avoids feature-laden classes high up in the hierarchy
• A decorator and its comonent aren't identical
• Lots of little objects!
Facade
Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level
interface that makes the subsystem easier to use.
Applicability
• Need to provide a simple interface to a complex system
• Need to decouple a subsystem from its clients
• Need to provide an interface to a software layer
Consequences
• Shields clients from subsystem components
• Promotes weak coupling between the subsystem and its clients
• Facade doesn't prevent clients from using subsystem classes if they need to
------------------------------------------------------------------------------------------------------------
Flyweight
DESIGN PATTERNS CATLOG 11
Use sharing to support large numbers of fine-grained objects efficiently.
Applicability
• An application uses a large number of objects
• Storage costs are high because of the sheer quantity of objects
• Most object state can be made extrinsic
• Many groups of objects may be replaced by relatively few shared objects once extrinsic
state is removed
• The application doesn't depend on object identity
Consequences
• Reduces the number of instances
• Most of the state must be extrinsic
------------------------------------------------------------------------------------------------------------
Proxy
Provide a surrogate or placeholder for another object to control access to it.
Applicabilty
DESIGN PATTERNS CATLOG 12
• Remote proxies can hide hide the fact that a real object is in another address space.
• Virtual proxies can create expensive objects on demand.
• Protection proxies can control access to an object.
• Smart references can preform additional action above a simple pointer.
DESIGN PATTERNS CATLOG 13
------------------------------------------------------------------------------------------------------------
Behavioural Patterns
------------------------------------------------------------------------------------------------------------
Chain of Responsibility
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to
handle the request. Chain the receiving objects and pass the request along the chain until an
object handles it.
Applicability
• More than one object may handle the reqest, and the handler isn't known.
• Need to avoid specifying the reciever of a request explictly.
• Need to specify the set of handlers dynamically.
Consequences
• Reduces coupling
• Added flexibility in assigning responsibilities to objects
• Receipt isn't guaranteed
------------------------------------------------------------------------------------------------------------
Command
Encapsulate a request as an object, thereby letting you parameterize clients with different
requests, queue or log requests, and support undoable operations.
DESIGN PATTERNS CATLOG 14
Applicability
• Need to replace callbacks by an object-oriented form
• Need to specify, queue, and execute requests at different times.
• Need to support undo
• Need to support logging chains
• Need to structure a system around high-level operations built on primitive operations
Consequences
• Decouples the object that invokes the operation from the one that knows how to perform
it.
• Commands become first-class objects
• Commands can be assembled into composite commands
• Easy to add new commands
------------------------------------------------------------------------------------------------------------
Interpreter
Given a language, define a representation for its grammar along with an interpreter that uses the
representation to interpret sentences in the language.
Applicability
• The grammar is simple
• Efficiency is not a critical concern
Consequences
• Easy to extend and change the grammar
• Implementing the grammar is easy
• Complex grammars are hard to maintain
• Easy to add new ways of interpreting the expressions
------------------------------------------------------------------------------------------------------------
DESIGN PATTERNS CATLOG 15
Iterator
Provide a way to access the elements of an aggregate object sequentially without exposing it
underlying representation. (See also STL Iterators for an example of iterator use with template
containers.)
Applicability
• Need to access an aggregate object's contents without exposing its internal representation
• Need to support multiple traversals of aggregate objects
• Need to provide a uniform interface for traversing different aggregate structures
Consequences
• Supports variation in the traversal of an aggregate
• Simplifies the Aggregate interface
• More than one traversal can be pending on an aggregate
------------------------------------------------------------------------------------------------------------
Mediator
Define an object that encapsulates how a set of objects interact. Mediator promotes loose
coupling by keeping objects from referring to each other explicitly, and it lets you vary their
interaction independently.
DESIGN PATTERNS CATLOG 16
Applicability
• Complex interaction exists, and you don't what to bury the interaction in the objects
• Reuse is difficult due to communciation paths
• Distributed behavior should be customizable without a lot of subclassing
Consequences
• Limits subclassing
• Decouples colleagues
• Simplifies object protocols
• Abstracts how objects cooperate
• Centralizes control
------------------------------------------------------------------------------------------------------------
Memento
Without violating encapsulation, capture and externalize an object's internal state so that the
object can be restored to this state later.
Applicability
• Need to save a "snapshot"
• Need to save state without exposing the implementation of an object
Consequences
• Preserves encapsulation boundaries
• Simplifies Originator
• Can have high storage costs
DESIGN PATTERNS CATLOG 17
Observer
Define a one-to-many dependency between objects so that when one object changes state, all its
dependents are notified and updated automatically.
Applicability
• Need to change other objects when one object changes state, but the other objects aren't
necessarily known to the one object
• Need to avoid tightly coupling an object with its observers
Consequences
• Abstract coupling between Subject and Observer
• Support for broadcast communciation
• Unexpected updates can be a significant performance hit
------------------------------------------------------------------------------------------------------------
State
Allow an object to alter its behavior when its internal state changes. The object will appear to
change its class.
Applicability
• Need to change an object's behavior when it changes its state
• Operations have large, multipart conditional statements that depend on the object's state
DESIGN PATTERNS CATLOG 18
Consequences
• Localizes state-specific behavior and partitions behavior for different states
• Makes state transitions explicit
• State objects can be shared if they have no intrinsic state (see Flyweight).
------------------------------------------------------------------------------------------------------------
Strategy
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy
lets the algorithms vary independently from clients that use it.
Applicability
• Need many related classes that differ only in their behavior
• Need different variants of an algorithm
• Need to hide algorithm data from the clients
• A class defines many behaviors and these appear as multiple conditional statements in its
operations. (See also State.)
Consequences
• Families of related algorithms
• An alternative to subclassing the Context
• Strategies eliminate conditional statements
• Allow choice of implementation
• Clients must be aware of different strategies
• Communication overhead between Strategy and Context may be high
• Increased number of objects
DESIGN PATTERNS CATLOG 19
Template Method
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template
Method lets subclasses redefine certain steps of an algorithm without changing the alorithm's
structure.
Applicability
• Need to implement the invariant parts of an algorithm, but leave some details to
subclasses
• Need to factor out common behavior in groups of subclasses
• Need to control subclass extensions
Consequences
• Fundamental technique for code reuse
• Often called hooks
• Template methods may be optional or required
DESIGN PATTERNS CATLOG 20
Visitor
Represent an operation to be performed on the elements of an object structure. Visitor lets you
define a new operation without changing the classes of the elements on which it operates.
Applicability
• Need to perform operations on the objects in a structure, and these objects have differing
interfaces
• Need to perform distrinct and unrelated operations on objects, and you want to avoid
"polluting" their classes with these operations
• Need to define new operations over a rarely-changing structure
Consequences
• Makes adding new operations easy
• Gathers related operations and separates unrelated ones
• Adding new ConcreteElements is hard
• Works across objects of differing types
• Can accumulate state
• May force a break in encapsulation
DESIGN PATTERNS CATLOG 21