You are on page 1of 13

OO Patterns Douglas C.

Schmidt

Patterns and Frameworks

Introduction to Patterns and Frameworks


 Motivation for Patterns and Frameworks
Douglas C. Schmidt  What is a Pattern? A Framework?
Professor Department of EECS  Pattern Categories
d.schmidt@vanderbilt.edu Vanderbilt University
www.cs.wustl.edu/schmidt/ (615) 343-8197  Pattern Examples

Vanderbilt University 1

OO Patterns Douglas C. Schmidt OO Patterns Douglas C. Schmidt

Motivation for Patterns and Frameworks Overview of Patterns and Frameworks


DX
BLOB
 Developing software is hard  Patterns support reuse of software architecture and design
STORE
 Developing reusable – Patterns capture the static and dynamic structures and
ATM software is even harder collaborations of successful solutions to problems that arise when
LAN

DIAGNOSTIC STATIONS  Proven solutions include building applications in a particular domain


patterns and frameworks  Frameworks support reuse of detailed design and code
ATM  www.cs.wustl.edu/schmidt/ – A framework is an integrated set of components that collaborate
MAN
CLUSTER
patterns.html to provide a reusable architecture for a family of related
ATM BLOB
LAN STORE
applications
 Together, design patterns and frameworks help to improve software
MODALITIES CENTRAL quality and reduce development time
(CT, MR, CR) BLOB STORE
– e.g., reuse, extensibility, modularity, performance

Vanderbilt University 2 Vanderbilt University 3


OO Patterns Douglas C. Schmidt OO Patterns Douglas C. Schmidt

Patterns of Learning Becoming a Chess Master


 First learn the rules
 Successful solutions to many areas of human endeavor are deeply
rooted in patterns – e.g., names of pieces, legal movements, chess board geometry
and orientation, etc.
– In fact, an important goal of education is transmitting patterns of
learning from generation to generation  Then learn the principles

 In a moment, we’ll explore how patterns are used to learn chess – e.g., relative value of certain pieces, strategic value of center
squares, power of a threat, etc.
 Learning to develop good software is similar to learning to play good
 However, to become a master of chess, one must study the
chess
games of other masters
– Though the consequences of failure are often far less dramatic!
– These games contain patterns that must be understood,
memorized, and applied repeatedly
 There are hundreds of these patterns

Vanderbilt University 4 Vanderbilt University 5

OO Patterns Douglas C. Schmidt OO Patterns Douglas C. Schmidt

Becoming a Software Design Master Design Patterns

 First learn the rules  Design patterns represent solutions to problems that arise when
– e.g., the algorithms, data structures and languages of software developing software within a particular context

 Then learn the principles – i.e., “Pattern == problem/solution pair in a context”

– e.g., structured programming, modular programming, object  Patterns capture the static and dynamic structure and collaboration
oriented programming, generic programming, etc. among key participants in software designs

 However, to become a master of software design, one must – They are particularly useful for articulating how and why to
study the designs of other masters resolve non-functional forces

– These designs contain patterns that must be understood,  Patterns facilitate reuse of successful software architectures and
memorized, and applied repeatedly designs

 There are hundreds of these patterns

Vanderbilt University 6 Vanderbilt University 7


OO Patterns Douglas C. Schmidt OO Patterns Douglas C. Schmidt

Example: Stock Quote Service Structure of the Observer Pattern


SUBJECT
Key Forces  Intent
REAL-TIME foreach o in observers loop
MODEL o.update()
MARKET
1. There may be many end loop Observer – Define a one-to-many
DATA FEED
observers 1 N update() dependency between
Subject observers objects so that when one
ION
2. Each observer may react ICAT
notify() APPL ENDENT
P object changes state, all
INDE
differently to the same attach(observer)
ION its dependents are
detach(observer) ICAT
APPL NDENT
notification DEPE
notified and updated
STOCK 3. The subject should be as Concrete automatically.
QUOTES Observer
decoupled as possible
Concrete update()
from the observers Subject subject

OBSERVERS get_state() subject->get_state()


 i.e., allow observers to
subject_state_
change independently of return subject_state_
the subject

Vanderbilt University 8 Vanderbilt University 9

OO Patterns Douglas C. Schmidt OO Patterns Douglas C. Schmidt

Graphical Notation Collaboration in the Observer Pattern

Concrete Concrete Concrete Variations


Subject Observer 1 Observer 2
PROCESS  “Push” architectures combine
THREAD set_state() control flow and data flow
notify()  “Pull” architectures separate
control flow from data flow
update()
OBJECT TEMPLATE
: CLASS CLASS get_state()

update()
get_state()

INHERITS CONTAINMENT

Vanderbilt University 10 Vanderbilt University 11


OO Patterns Douglas C. Schmidt OO Patterns Douglas C. Schmidt

Design Pattern Descriptions Frameworks


Main parts Pattern descriptions are
often independent of 1. Frameworks are semi-complete applications
1. Name and intent
programming language or  Complete applications are developed by inheriting from, and
2. Problem and context implementation details instantiating parameterized framework components
3. Force(s) addressed  Contrast with 2. Frameworks provide domain-specific functionality
frameworks
4. Abstract description of structure and  e.g., business applications, telecommunication applications,
collaborations in solution window systems, databases, distributed applications, OS kernels
5. Positive and negative 3. Frameworks exhibit inversion of control at run-time
consequence(s) of use
 i.e., the framework determines which objects and methods to
6. Implementation guidelines and invoke in response to events
sample code
7. Known uses and related patterns

Vanderbilt University 12 Vanderbilt University 13

OO Patterns Douglas C. Schmidt OO Patterns Douglas C. Schmidt

Class Libraries vs. Frameworks vs. Patterns Component Integration in Frameworks


APPLICATION- LOCAL
SPECIFIC INVOCATIONS
MATH
CLASSES
Definition
FUNCTIONALITY
ADT
 Framework components are loosely
CLASSES DATABASE  Class libraries APPLICATION coupled via callbacks
CLASSES
CODE
EVENT GLUE
GUI
CLASSES
NETWORK – Self-contained, “pluggable” ADTs  Callbacks allow independently developed
LOOP CODE IPC
CLASSES
 Frameworks EVENT software components to be connected
(A) CLASS LIBRARY ARCHITECTURE HANDLER(S) together
– Reusable, “semi-complete”
NETWORKING
EVENT callback()  Callbacks provide a connection-point where
LOOP
applications
ADT DISPATCHER generic framework objects can
CLASSES GUI
APPLICATION-
CALL
 Patterns EVENT LOOP communicate with application objects
INVOKES SPECIFIC BACKS
FUNCTIONALITY EVENT
MATH LOOP
– Problem, solution, context EVENT SENSOR – The framework provides the common
CLASSES

EVENT
SYSTEM template methods and the application
DATABASE CODE
LOOP
provides the variant hook methods
(B) FRAMEWORK ARCHITECTURE

Vanderbilt University 14 Vanderbilt University 15


OO Patterns Douglas C. Schmidt OO Patterns Douglas C. Schmidt

Comparing Patterns and Frameworks Design Pattern Space


Reactor/Proactor State Singleton  Patterns and frameworks
 Creational patterns
Strategy

I/O Strategy Cached Virtual


Framework Filesystem are highly synergistic
– i.e., neither is – Deal with initializing and configuring classes and objects
Asynchronous Completion Token Tilde ~
Protocol
Expander
/home/... subordinate  Structural patterns
Acceptor

Strategy
Handler Event Dispatcher

Protocol  Patterns can be – Deal with decoupling interface and implementation of classes and
Filter
characterized as more objects
Adapter
abstract descriptions of

Active Object
frameworks, which are  Behavioral patterns
Concurrency
Protocol Pipeline
Framework
Strategy
Framework implemented in a particular – Deal with dynamic interactions among societies of classes and
Streams Service Configurator
language objects

In general, sophisticated frameworks embody dozens of patterns and


patterns are often used to document frameworks

Vanderbilt University 16 Vanderbilt University 17

OO Patterns Douglas C. Schmidt OO Patterns Douglas C. Schmidt

Creational Patterns Structural Patterns


 Factory Method
 Adapter
– Method in a derived class creates associates
– Translator adapts a server interface for a client
 Abstract Factory
 Bridge
– Factory for building related objects
 Builder – Abstraction for binding one of many implementations

– Factory for building complex objects incrementally  Composite


 Prototype – Structure for building recursive aggregations
– Factory for cloning new instances from a prototype  Decorator
 Singleton – Decorator extends an object transparently
– Factory for a singular (sole) instance

Vanderbilt University 18 Vanderbilt University 19


OO Patterns Douglas C. Schmidt OO Patterns Douglas C. Schmidt

Structural Patterns (cont’d) Behavioral Patterns

 Facade  Chain of Responsibility


– Facade simplifies the interface for a subsystem – Request delegated to the responsible service provider
 Flyweight  Command
– Many fine-grained objects shared efficiently – Request as first-class object
 Proxy  Interpreter
– One object approximates another – Language interpreter for a small grammar
 Iterator
– Aggregate elements are accessed sequentially

Vanderbilt University 20 Vanderbilt University 21

OO Patterns Douglas C. Schmidt OO Patterns Douglas C. Schmidt

Behavioral Patterns (cont’d) Behavioral Patterns (cont’d)

 Mediator  Strategy
– Mediator coordinates interactions between its associates – Abstraction for selecting one of many algorithms
 Memento  Template Method
– Snapshot captures and restores object states privately – Algorithm with some steps supplied by a derived class
 Observer  Visitor
– Dependents update automatically when a subject changes – Operations applied to elements of an heterogeneous object
structure
 State
– Object whose behavior depends on its state

Vanderbilt University 22 Vanderbilt University 23


OO Patterns Douglas C. Schmidt OO Patterns Douglas C. Schmidt

When to Use Patterns What Makes a Pattern a Pattern?


1. Solutions to problems that recur with variations A pattern must:
 No need for reuse if the problem only arises in one context  Solve a problem,  Teach

2. Solutions that require several steps – i.e., it must be useful! – It must provide sufficient
understanding to tailor the
 Not all problems need all steps  Have a context,
solution
 Patterns can be overkill if solution is simple linear set of – It must describe where the
instructions  Have a name
solution can be used
3. Solutions where the solver is more interested in the existence of the – It must be referred to
 Recur,
solution than its complete derivation consistently
– It must be relevant in other
 Patterns leave out too much to be useful to someone who really situations
wants to understand
– They can be a temporary bridge, however

Vanderbilt University 24 Vanderbilt University 25

Do

SUPERVISOR
HANDLERS
SUPER-
OO Patterns Douglas C. Schmidt

VISOR

 www.cs.wustl.edu/schmidt/PDF/DSEJ-94.pdf
Case Study: A Reusable Object-Oriented

CALL CENTER

 OO framework for Call Center Management

 www.cs.wustl.edu/schmidt/PDF/ECOOP-
MANAGER
Communication Software Framework

: Reactor
 Developing portable, reusable, and efficient communication software

SUPER-
System Overview

VISOR
is hard

HANDLERS
SWITCH
 OS platforms are often fundamentally incompatible

NETWORK
– e.g., different concurrency and I/O models
 Thus, it may be impractical to directly reuse: SUPER-
VISOR

SERVER
EVENT
– Algorithms
– Detailed designs
– Interfaces

Vanderbilt University
– Implementations
SUPER-

ERICSSON
VISOR

TELECOM

95.pdf
SWITCHES
OO Patterns

ERICSSON

MD110
MD110

Vanderbilt University 26
OO Patterns Douglas C. Schmidt OO Patterns Douglas C. Schmidt

Problem: Cross-platform Reuse Solution: Reuse Design Patterns


Protocol Handlers (HTTP)  OO framework was first developed  Patterns support reuse of
Publisher
on UNIX and later ported to Subscriber software architecture
Windows NT 3.51 in 1993
Pipes &  Patterns embody
Layers
WaitForCompletion()  UNIX and Windows NT have Filters successful solutions to
I/O fundamentally different I/O models Acceptor- Component
problems that arise when
Subsystem Connector developing software in a
I/O Completion
Configurator
Port – i.e., synchronous vs.
particular context
asynchronous STRATEGIC
read() write() read() write() read() read() accept()
PATTERNS
Reactor
 Patterns reduced project
 Thus, direct reuse of original
TACTICAL
risk by leveraging proven
framework was infeasible Factory Proxy Wrapper
PATTERNS Iterator Composite Method Facade design expertise
– Later solved by ACE and
Windows NT 4.0

Vanderbilt University 28 Vanderbilt University 29

OO Patterns Douglas C. Schmidt OO Patterns Douglas C. Schmidt

The Reactor Pattern Collaboration in the Reactor Pattern


Reactor select (handles); Intent callback :
handle_events() foreach h in handles loop main Concrete Reactor  Note inversion of
table[h].handle_event(type) program Event_Handler
register_handler(h) end loop  Decouples Reactor()
control

INITIALIZATION
remove_handler(h) handlers
synchronous event INITIALIZE
1 N Event Handler register_handler(callback)  Also note how

MODE
uses Handle owns handle_event(type) demuxing & dispatching REGISTER HANDLER
get_handle() long-running
get_handle() from event handling EXTRACT HANDLE
notifies handle_events() event handler
START EVENT LOOP
Forces Resolved select()
callbacks can
Synchronous Event Concrete FOREACH EVENT DO
Demultiplexer degrade quality
Event  Efficiently demux handle_input()
EVENT HANDLING

DATA ARRIVES of service


select() Handler
events synchronously handle_output()
OK TO SEND
www.cs.wustl.edu/schmidt/POSA/ within one thread
MODE

handle_signal()
SIGNAL ARRIVES

 Extending applications TIMER EXPIRES


handle_timeout()
without changing remove_handler(callback)
REMOVE HANDLER
demux infrastructure CLEANUP
handle_close()

Vanderbilt University 30 Vanderbilt University 31


Do

(&eh, ACE_Event_Handler::READ_MASK);
OO Patterns Douglas C. Schmidt

Using ACE’s Reactor Pattern Implementation

int main (int argc, char *argv[])


Using ACE’s Reactor Pattern
Implementation (cont’d)
#include "ace/Reactor.h"

reactor.handle_events ();
class My_Event_Handler : public ACE_Event_Handler {
public:

reactor.register_handler

reactor.register_handler
virtual int handle_input (ACE_HANDLE h) {
cout << "input on handle " << h << endl;

My_Event_Handler eh;
ACE_Reactor reactor;
return 0; }
virtual int handle_signal (int signum,

/* NOTREACHED */
(SIGINT, &eh);
siginfo_t *,
ucontext_t *) {
cout << "signal " << signum << endl;

return 0;
return 0; }

Vanderbilt University
for (;;)
virtual ACE_HANDLE get_handle (void) const {
return ACE_STDIN; }

OO Patterns
};

}
Vanderbilt University 32

OO Patterns Douglas C. Schmidt OO Patterns Douglas C. Schmidt

Differences Between UNIX and Windows NT Lessons Learned from Case Study
 Reactive vs. Proactive I/O
– Reactive I/O is synchronous  Real-world constraints of OS platforms can preclude direct reuse of
– Proactive I/O is asynchronous communication software
 Requires additional interfaces to “arm” the I/O mechanism – e.g., must often use non-portable features for performance
– See Proactor pattern
 www.cs.wustl.edu/schmidt/POSA/  Reuse of design patterns may be the only viable means to leverage
previous development expertise
 Other differences include
 Design patterns are useful, but are no panacea
– Resource limitations
 e.g., Windows WaitForMultipleObjects() limits – Managing expectations is crucial
HANDLEs per-thread to 64 – Deep knowledge of platforms, systems, and protocols is also very
– Demultiplexing fairness important
 e.g., WaitForMultipleObjects always returns the lowest
active HANDLE

Vanderbilt University 34 Vanderbilt University 35


OO Patterns Douglas C. Schmidt OO Patterns Douglas C. Schmidt

Key Principles Planning for Change

 Successful patterns and frameworks can be boiled down to a few  Often, aspects of a design “seem” constant until they are examined
key principles: in the light of the dependency structure of an application
1. Separate interface from implementation – At this point, it becomes necessary to refactor the framework or
2. Determine what is common and what is variable with an interface pattern to account for the variation
and an implementation
 Frameworks often represent the distinction between commonality
– Common == stable
and variability via template methods and hook methods, respectively
3. Allow substitution of variable implementations via a common
interface
 Dividing commonality from variability should be goal-oriented rather
than exhaustive

Vanderbilt University 36 Vanderbilt University 37

OO Patterns Douglas C. Schmidt OO Patterns Douglas C. Schmidt

The Open/Closed Principle The Open/Closed Principle (cont’d)

 Determining common vs. variable components is important  Components should be:


– Insufficient variation makes it hard for users to customize – open for extension
framework components – closed for modification
– Conversely, insufficient commonality makes it hard for users to
 Impacts
comprehend and depend upon the framework’s behavior
– Abstraction is good
 In general, dependency should always be in the direction of stability
– Inheritance and polymorphism are good
– i.e., a software component should not depend on any component – Public data members and global data are bad
that is less stable than itself – Run-time type identification can be bad
 The “Open/Closed” principle
– This principle allows the most stable component to be extensible

Vanderbilt University 38 Vanderbilt University 39


OO Patterns Douglas C. Schmidt OO Patterns Douglas C. Schmidt

Violation of Open/Closed Principle Application of Open/Closed Principle


struct Shape { enum Type { CIRCLE, SQUARE } class Shape {
shape_type; public:
/* . . . */ }; virtual void draw () const = 0;
void draw_square (const Square &); };
void draw_circle (const Circle &);
class Square : public Shape { /* . . . */ };
void draw_shape (const Shape &shape) { class Circle : public Shape { /* . . . */ };
switch (shape.shape_type) {
case SQUARE: typedef vector<Shape> Shape_Vector;
draw_square ((const Square &) shape);
break; void draw_all (const Shape_Vector &shapes) {
case CIRCLE: for (Shape_Vector::iterator i = shapes.begin();
draw_circle ((const Circle &) shape); i != shapes.end ();
break; i++)
// etc. (*iterator).draw ();
}

Vanderbilt University 40 Vanderbilt University 41

OO Patterns Douglas C. Schmidt OO Patterns Douglas C. Schmidt

Benefits of Design Patterns Drawbacks to Design Patterns

 Design patterns enable large-scale reuse of software  Patterns do not lead to direct code reuse
architectures
 Patterns are deceptively simple
– They also help document systems to enhance understanding
 Teams may suffer from pattern overload
 Patterns explicitly capture expert knowledge and design
 Patterns are validated by experience and discussion rather
tradeoffs, and make this expertise more widely available
than by automated testing
 Patterns help improve developer communication
 Integrating patterns into a software development process is a
– Pattern names form a vocabulary human-intensive activity
 Patterns help ease the transition to object-oriented technology

Vanderbilt University 42 Vanderbilt University 43


OO Patterns Douglas C. Schmidt OO Patterns Douglas C. Schmidt

Tips for Using Patterns Effectively Lessons Learned using OO Frameworks

 Do not recast everything as a pattern.  Benefits of frameworks


– Instead, develop strategic domain patterns and reuse existing – Enable direct reuse of code
tactical patterns – Facilitate larger amounts of reuse than stand-alone functions or
individual classes
 Institutionalize rewards for developing patterns
 Drawbacks of frameworks
 Directly involve pattern authors with application developers
and domain experts – High initial learning curve
 Many classes, many levels of abstraction
 Clearly document when patterns apply and do not apply
– The flow of control for reactive dispatching is non-intuitive
 Manage expectations carefully – Verification and validation of generic components is hard

Vanderbilt University 44 Vanderbilt University 45

OO Patterns Douglas C. Schmidt OO Patterns Douglas C. Schmidt

Patterns and Framework Literature Conferences and Workshops on Patterns


 Books
 Pattern Language of Programs Conferences
– Gamma et al., Design Patterns: Elements of Reusable
Object-Oriented Software AW, ’94 – September 8-12, 2003, Monticello, Illinois, USA
– Pattern Languages of Program Design series by AW, ’95-’99. – http://hillside.net/conferences/plop.htm
– Siemens & Schmidt, Pattern-Oriented Software Architecture,
 The European Pattern Languages of Programming conference
Wiley, volumes ’96 & ’00 (www.posa.uci.edu)
– Schmidt & Huston, C++ Network Programming: Mastering – June 25-29, 2003, Kloster Irsee, Germany
Complexity with ACE and Patterns, AW, ’02 – http://hillside.net/conferences/europlop.htm
(www.cs.wustl.edu/˜schmidt/ACE/book1/)
– Schmidt & Huston, C++ Network Programming: Systematic  Middleware 2003
Reuse with ACE and Frameworks, AW, ’03 – June 16-20, 2003, Rio, Brazil
(www.cs.wustl.edu/˜schmidt/ACE/book2/)
– www.cs.wustl.edu/ schmidt/activities-chair.html

Vanderbilt University 46 Vanderbilt University 47


OO Patterns Douglas C. Schmidt

Summary
 Mature engineering disciplines have handbooks that describe
successful solutions to known problems
– e.g., automobile designers don’t design cars using the laws of
physics, they adapt adequate solutions from the handbook known
to work well enough
– The extra few percent of performance available by starting from
scratch typically isn’t worth the cost
 Patterns can form the basis for the handbook of software
engineering
– If software is to become an engineering discipline, successful
practices must be systematically documented and widely
disseminated

Vanderbilt University 48

You might also like