Transcript Document

CSCE 606:
(Object Oriented)
Design Patterns
Some material from R. Martin, Bruegge, Dutoit
Outline
• Context
• Some key concepts and notions of OO
• Design patterns
• A few more design patterns
• Idioms
• Summary
7/17/2015
CSCE 606 OO Design Patterns
2
Context
1. Requirements elicitation
 Functional model (use cases, formal specifications etc.)
 Non-functional requirements
2. Analysis
 Analysis Object Model (class diagrams)
 Dynamic Model (state charts, sequence diagrams)
3. System design (we have not discussed yet)
 Design goals
 Subsystem decomposition
4. Object design
 Object design model (class diagrams)
5. Implementation
 Source code
6. Testing
 Deliverable system
7/17/2015
CSCE 606 OO Design Patterns
3
System Design (One Slide Version)
• Subsystem decomposition
• Abstraction of the machine(s)
• Choosing middleware, GUI frameworks, class
libraries, database engines
• Application domain components
• Possibly choosing off-the-shelf application domain
components for select domain functionality
• Object design to fill in the rest
• Adapt reusable components
• Identify new solution classes
• Specify subsystem interfaces precisely
7/17/2015
CSCE 606 OO Design Patterns
4
Object Design
• Purpose
• Prepare for implementing the system model
• Transform the system model for better
implementability/extensibility/performance/. . .
• Explore ways to implement the system
model
• The result of object design should match
the structure of the implementation
7/17/2015
CSCE 606 OO Design Patterns
5
Activities
• Reuse: identify and adapt existing solutions
• Off-the-shelf components
• Libraries
• Design patterns
• Interface specification
• Specs of each class interface
• APIs of subsystems
• Object model restructuring
• To improve some characteristics (extensibility,
understandability, etc.)
• Object model optimization
• Greater speed, lower memory use, etc.
7/17/2015
CSCE 606 OO Design Patterns
6
Outline
• Context
• Some key concepts and notions of OO
• Design patterns
• A few more design patterns
• Idioms
• Summary
7/17/2015
CSCE 606 OO Design Patterns
7
Outline
• Some principles of object-oriented
programming
•
•
•
•
About modularity
OO twists on modularity, inheritance
Substitutability
Delegation
• Introduction to design patterns
• A few design patterns
7/17/2015
CSCE 606 OO Design Patterns
8
Modularity
• Parnas, On the Criteria to be Used in
Decomposing Systems into Modules, 1972
• Every module should be known to the outside world
through an official, “public” interface
• The rest of the module’s properties comprises its
“secrets”
• It should be impossible to access the secrets from the
outside
• Inheritance, encapsulation, related features in OO
languages aimed at supporting information hiding
• Aside: Parnas says the following about OO languages
• Could be helpful, but not really needed
• Language is not the issue, design is what matters
• Some features make it easy to do things wrong
7/17/2015
CSCE 606 OO Design Patterns
9
Characteristics of Good
Modularization
• Low coupling and high cohesion
• Minimize dependencies
• Changes are localized
• Maximize unity
• Modules work well together
7/17/2015
CSCE 606 OO Design Patterns
10
Encapsulation
• Booch
The process of compartmentalizing the elements of
an abstraction that constitute its structure and
behavior; encapsulation serves to separate the
contractual interface of an abstraction and its
implementation
• Casual definition: bundling data and methods,
with access protection
• Encapsulation enables object invariants to be
enforced
7/17/2015
CSCE 606 OO Design Patterns
11
Inheritance
• Where used:
1. Organization (during analysis)
• Inheritance helps in expressing generalization and
specialization in taxonomies that deal with the
application domain
• Primary use: discussion with domain experts and
customers
2. Reuse (during object design)
• Inheritance helps in reusing models and code to deal
with the solution domain
• Goal is to reduce redundancy and obtain extensibility
• Primary use: developers
7/17/2015
CSCE 606 OO Design Patterns
12
Implementation vs. Interface
Inheritance
• Implementation inheritance
• Also called class inheritance
• Goal is to extend an applications’ functionality by reusing
functionality from the superclass
• Inherit from an existing class with some or all operations
already implemented
• Specification inheritance
• Also called subtyping
• Inherit a specification for which to provide an
implementation
• The specification is an abstract class with all the
operations specified but not yet implemented
• Meyer gives a taxonomy of 13 different kinds of
uses of inheritance
7/17/2015
CSCE 606 OO Design Patterns
13
Extensibility: Open Closed
Principle (OCP)
A module should be open for extension but
closed for modification
- B. Meyer (OOSC98)
• Essentially suggests that defining new
subclasses should suffice to evolve code
• (maybe in Eiffel, as its type system gives
considerable freedom)
• Nice if works
• Requires guessing/knowing the variation points
• Requires obeying Liskov Substitution Principle
7/17/2015
CSCE 606 OO Design Patterns
14
Liskov Substitution Principle
• Simple formulation
Subclasses should be substitutable for their base classes
• Somewhat more precise formulation
• Note that notion of subtyping is behavioral
• Cannot be checked
Let q(x) be a property provable about objects x of type T.
Then q(y) should be provable for objects y of type S where S is
a subtype of T
- Liskov, Wing, 1994
• Same in code
class Base { . . . };
class Derived : public Base { . . . };
void q(Base& b); // should work, even if b an
// instance of Derived
7/17/2015
CSCE 606 OO Design Patterns
15
LSP Violation
• “Circle is-an ellipse”
class circle : public ellipse {
...
void set_foci ( Point p1 , Point p2) { a = p1; b = p1 }
}
void f( Ellipse & e) {
Point a( -1 ,0) , b (1 ,0);
e.set_foci (a, b);
assert (e.get_focus_a () == a);
assert (e.get_focus_b () == b);
}
• set_foci’s postcondition (something like a == p1, b == p2) not true for circles
• Fixes at the client calling f easily lead to Open Closed Principle violations
7/17/2015
CSCE 606 OO Design Patterns
16
LSP and Design by Contract
class A {
@invariant i1;
@pre p1;
virtual void foo (...);
@post q1
}
class B : public A {
@invariant i2;
@pre p2;
void foo (...);
@post q2
}
• What are the relations?
p1?p2
q1?q2
i1?i2
7/17/2015
p1  p2
q1  q2
i1  i2
• A method in a derived class
must
• Have preconditions that
are no stronger than
those of the base’s
method it is overriding
• Have postconditions no
weaker than those of the
base’s method it is
overriding
• “derived methods should
expect no more and provide
no less”
CSCE 606 OO Design Patterns
17
Inheritance vs. Delegation
Consider this inheritance relation:
Implementation inheritance vs. delegation
class HashTable {
void put ( Object key , Object element );
class MySet {
private Hashtable table ;
Object get ( Object key );
MySet () {
boolean containsKey ( Object );
table = Hashtable ();
boolean containsValue ( Object );
}
...
void put ( Object element ) {
}
if (! containsValue ( element )) {
class MySet extends HashTable {
table.put ( element , this );
void put ( Object element ) {
}
if (! containsKey ( element )) {
}
put ( element , this );
boolean containsValue ( Object element ) {
}
return table.containsKey ( element );
}
}
boolean containsValue ( Object element ) {
return containsKey ( element );
}
...
}
...
}
7/17/2015
CSCE 606 OO Design Patterns
18
Inheritance vs. Delegation
• Inheritance should be used only if real
taxonomies exist
• If LSP (roughly) holds
• Delegation should be preferred when reusing
implementations
• Next: design patterns
• And we will notice that most design patterns are
some compositions/combinations of delegation and
inheritance
7/17/2015
CSCE 606 OO Design Patterns
19
Outline
• Context
• Some key concepts and notions of OO
• Design patterns
• A few more design patterns
• Idioms
• Summary
7/17/2015
CSCE 606 OO Design Patterns
20
Design Patterns Motivation
• Not every problem solved with a solution
developed “from scratch”
• Desirable to reuse solutions
• Recording and cataloging experience in SW
design often not done systematically, or at all
• Learning how to design starts by studying other
designs
7/17/2015
CSCE 606 OO Design Patterns
21
Characterizing Design Patterns
• Reusable designs
• Capturing design knowledge that
• Is too “high-level” to write as an abstraction in a library
• What is too high-level depends on the language, of course
• Modifiable abstractions/designs
• Basic idea: avoid “re-inventing the wheel”
• Capture well-tested solutions to oft-occurring
situations
• Modularize design!
7/17/2015
CSCE 606 OO Design Patterns
22
Design Pattern
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.
Visually pleasing and practical structures for an application
and/or setting could be described by a pattern language.
- Christopher Alexander
• For example, desirable farmhouses in the Bernese
Oberland area of Switzerland used these patterns:
North-South Axis
West-Facing Entrance Down the Slope
Two Floors
Hay Loft at the Back
Bedrooms in Front
7/17/2015
CSCE 606 OO Design Patterns
Garden to the South
Pitched Roof
Half-Hipped End
Balcony Toward the Garden
Carved Ornaments
23
Patterns in Software
• OOPSLA 1987, Kent Beck and Ward Cunningham,
Using Pattern Languages for Object-Oriented
Programs
• Applied Alexander’s pattern language to UI design
•
•
•
•
•
Window Per Task
Few Panes Per Window
Standard Panes
Short Menus
Nouns and Verbs
• More work followed, culminating to the Design
Patterns book in 1995
7/17/2015
CSCE 606 OO Design Patterns
24
GoF Book
7/17/2015
CSCE 606 OO Design Patterns
25
23 Patterns in GoF Book
Creational
Structural
Behavioral
Factory Method
Adapter
Command
Abstract Factory
Façade
Visitor
Prototype
Proxy
Iterator
Builder
Decorator
Interpreter
Singleton
Composite
Mediator
Flyweight
Memento
Bridge
Observer
Strategy
Template Method
Chain of Responsibility
State
7/17/2015
CSCE 606 OO Design Patterns
26
Creational Patterns
Builder
Factory method
Abstract Factory
Prototype
Singleton
7/17/2015
Separates construction from
representation (how to build, e.g.,
Composite objects)
Create objects without hardcoding the
class name
Groups factories with a common
theme
Cloning from prototypes
Restricts objects to no more than one
instance, with a single point of access
CSCE 606 OO Design Patterns
27
Structural Patterns
Adapter
Bridge
Composite
Decorator
Façade
Flyweight
Proxy
7/17/2015
Creates a new interface for an existing
unmodifiable interface
Separates an abstraction form its implementation
Tree structure of objects that allows uniform
manipulation
Dynamically extensible behavior (instead of
statically, as with subclassing)
Unified interface to simplify use (wrap APIs, etc.)
Share similar data among many objects
A class serving as a placeholder, possibly adding
functionality, to another class
CSCE 606 OO Design Patterns
28
Behavioral Patterns
Chain of Responsibility
Command
Interpreter
Iterator
Mediator
Memento
Observer
State
Strategy
Template method
Visitor
7/17/2015
Delegate command objects to a chain of processing
objects
Wrap a command into an object with all the information
that is needed to execute it
How to interpret ASTs represented as Composite
Objects
Access objects sequentially without exposing the
underlying representation
Encapsulate, and restrict the form of, communication
between objects into a dedicated middleman
Undo functionality
Publish/subscribe
Object behavior changes when state changes (modes)
Select most suitable algorithm at runtime
Algorithm skeleton, with subclasses providing concrete
behavior
Separate algorithm from structure of the object it
operates on (double dispatching)
CSCE 606 OO Design Patterns
29
Structure of a Design Pattern
• Four elements
• A unique name
• A problem description
• Situations in which the pattern applies
• Problems addressed
• A solution
• Stated as a set of collaborating classes and interfaces
• Often uses class diagrams, sequence diagrams, state
charts, etc.
• A set of consequences that describes the tradeoffs and alternatives w.r.t. the design goals the
pattern addresses
7/17/2015
CSCE 606 OO Design Patterns
30
GoF Book’s Pattern Structure
• Pattern Name and Classification
• Intent
•
“Why use this pattern?”
• Also known as
• Motivation (Forces)
•
Often an example scenario
• Applicability
• Structure
•
Often class and interaction diagrams
• Participants
•
Classes and objects involved, and their roles
• Collaborations
•
How classes/objects interact
• Consequences
• Implementation
• Sample Code
•
Concrete example of how to use the pattern (in code)
• Known Uses
• Related Patterns
7/17/2015
CSCE 606 OO Design Patterns
31
Composite Pattern: Motivation
There are times when a program needs to manipulate a
tree data structure and it is necessary to treat both
Branches as well as Leaf Nodes uniformly. Consider for
example a program that manipulates a file system. A file
system is a tree structure that contains Branches which
are Folders as well as Leaf nodes which are Files. Note
that a folder object usually contains one or more file or
folder objects and thus is a complex object where a file is
a simple object. Note also that since files and folders
have many operations and attributes in common, such
as moving and copying a file or a folder, listing file or
folder attributes such as file name and size, it would be
easier and more convenient to treat both file and folder
objects uniformly by defining a File System Resource
Interface.
7/17/2015
CSCE 606 OO Design Patterns
32
Composite Pattern: Intent
• The intent of this pattern is to compose objects
into tree structures to represent part-whole
hierarchies
• Composite lets clients treat individual objects
and compositions of objects uniformly
7/17/2015
CSCE 606 OO Design Patterns
33
Composite Pattern:
Implementation & Participants
Component Component is the abstraction for leafs and composites. It defines the interface that must be
implemented by the objects in the composition. For example a file system resource defines move, copy,
rename, and getSize methods for files and folders.
Leaf
Leafs are objects that have no children. They implement services described by the Component
interface. For example a file object implements move, copy, rename, as well as getSize methods which
are related to the Component interface.
Composite A Composite stores child components in addition to implementing methods defined by the component
interface. Composites implement methods defined in the Component interface by delegating to child
components. In addition composites provide additional methods for adding, removing, as well as getting
components.
Client
The client manipulates objects in the hierarchy using the component interface. A client has a reference
to a tree data structure and needs to perform operations on all nodes independent of the fact that a
node might be a branch or a leaf. The client simply obtains reference to the required node using the
component interface, and deals with the node using this interface; it doesn’t matter if the node is a
composite or a leaf.
7/17/2015
CSCE 606 OO Design Patterns
34
Composite Pattern:
Applicability
• The composite pattern applies when there is a
part-whole hierarchy of objects and a client
needs to deal with objects uniformly regardless
of the fact that an object might be a leaf or a
branch
7/17/2015
CSCE 606 OO Design Patterns
35
Example – Graphics Drawing
Editor
• In graphics editors a graphic can be basic or complex. Examples
of simple graphics are lines and circles, where a complex graphic
is a picture containing many simple (or complex) graphics. Since
simple and complex shapes have operations in common, such as
rendering the graphic to a screen, and since graphics follow a
part-whole hierarchy, composite pattern can be used to enable the
program to deal with all graphics uniformly.
7/17/2015
CSCE 606 OO Design Patterns
36
Example – Graphics Drawing
Editor
In the example we can see the following actors:
Graphic (Component) Graphic is the abstraction for Line, Circle, etc. objects, (leafs) and
Picture objects (composites).
Line, Circle (Leafs)
Objects that have no children. They implement services described by the
Graphic interface.
Picture (Composite)
A Composite stores child Graphic objects in addition to implementing
methods defined by the Graphic interface.
Client
The Client (such as a graphical editor) manipulates Graphics in the
hierarchy.
7/17/2015
CSCE 606 OO Design Patterns
37
Composite Pattern: Alternative
Implementation
Some methods only make sense for Composite objects,
such as Add, Remove, and getChild, and in the class
diagram above are thus only defined for Composite
objects. Prior to calling these methods, one has to cast a
Component to a Composite. Alternatively, these methods
could be defined in Component, with default
implementations that would do nothing.
7/17/2015
CSCE 606 OO Design Patterns
38
Composite Pattern:
Consequences
• The composite pattern defines class hierarchies
consisting of primitive objects and composite objects.
Primitive objects can be composed into more
complex objects, which in turn can be composed.
• Clients treat primitive and composite objects
uniformly through a component interface which
makes client code simple.
• Adding new components can be easy and client
code does not need to be changed since client deals
with the new components through the component
interface.
7/17/2015
CSCE 606 OO Design Patterns
39
Composite Pattern: Related
Patterns
• Decorator Pattern
• Decorator is often used with Composite. When
decorators and composites are used together, they
will usually have a common parent class. So
decorators will have to support the Component
interface with operations like Add, Remove, and
GetChild.
7/17/2015
CSCE 606 OO Design Patterns
40
Composite Pattern: Known
Uses
• File system implementation as discussed
previously
• Graphics editors as discussed previously
7/17/2015
CSCE 606 OO Design Patterns
41
Observations
• Design patterns make use of interfaces,
information hiding, polymorphism, indirection
• A pattern typically consists of several classes
that may have complex associations
• Design patterns can thus make a design more
complex, and decrease performance
• The tradeoff between added complexity and
the potential pay-offs (modularity, extensibility,
portability, etc.) needs to be considered
7/17/2015
CSCE 606 OO Design Patterns
42
Outline
• Context
• Some key concepts and notions of OO
• Design patterns
• A few more design patterns
• Idioms
• Summary
7/17/2015
CSCE 606 OO Design Patterns
43
Factory Method
• Intent
• Define an interface for creating an object, but let
subclasses decide which class to instantiate.
Factory Method lets a class defer instantiation to
subclasses.
• Defining a virtual constructor.
• The new operator considered harmful.
7/17/2015
CSCE 606 OO Design Patterns
44
Example Problem
• A framework needs to standardize the
architectural model for a range of applications,
but allow for individual applications to define
their own domain objects and provide for their
instantiation.
7/17/2015
CSCE 606 OO Design Patterns
45
Visitor Pattern
• Intent
• 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.
• The classic technique for recovering lost type information.
• Do the right thing based on the type of two objects.
• Double dispatch
• Problem
Many distinct and unrelated operations need to be performed on
node objects in a heterogeneous aggregate structure. You want
to avoid “polluting” the node classes with these operations. And,
you do not want to have to query the type of each node and cast
the pointer to the correct type before performing the desired
operation.
7/17/2015
CSCE 606 OO Design Patterns
46
Visitor Pattern
• A “static” class hierarchy, possibly tree-like, expressed
using the Composite Pattern
• Each class in this hierarchy defines an
accept(visitor&) method
• accept methods send this pointer to the visitor
• visitor abstract base class
• containing visit(a) overload for each class a in the static
hierarchy
• Each derived class of visitor implements some of the
visit() overloads
• Traversal pattern can be either fixed in the accept
methods, or left to be expressed in the visit methods
7/17/2015
CSCE 606 OO Design Patterns
47
Visitor Pattern: Class Diagram
7/17/2015
CSCE 606 OO Design Patterns
48
Visitor Pattern: Sequence
Diagram
7/17/2015
CSCE 606 OO Design Patterns
49
Outline
• Context
• Some key concepts and notions of OO
• Design patterns
• A few more design patterns
• Idioms
• Summary
7/17/2015
CSCE 606 OO Design Patterns
50
Idioms
• Expression of a simple task that is not built-in
into a language
• Pimpl-idiom
class Handle {
private :
class Body * pimpl ; // opaque pointer
// Body forward - declared
};
• Also: a non-obvious use of a particular feature
of a language
for (;;) { action (); }
7/17/2015
CSCE 606 OO Design Patterns
51
Idioms
• Like design patterns, but
• Language dependent
• Usually of smaller scope
7/17/2015
CSCE 606 OO Design Patterns
52
Example: RAll
• “Resource Acquisition is Initialization”
• One description in pattern form:
• From Kevlin Henney, Execute-Around Object. C++
Patterns: Executing Around Sequences. EuroPLoP
2000: 431-454
Define a helper object that executes actions before
and after a sequence of statements in its
constructor(s) and destructor.
• Example: Critical Sections
7/17/2015
CSCE 606 OO Design Patterns
53
RAII Example
class mutex {
public :
void lock ();
void unlock ();
...
}
resource shared ;
mutex quard ;
guard.lock ();
.... // use shared  Exception!
guard.unlock ();
7/17/2015
guard . lock ();
try
{
... // use shared
}
catch (...)
{
guard.unlock ();
throw ;
}
guard.unlock ();
CSCE 606 OO Design Patterns
54
RAII Example
template < typename lockee >
class mutex {
class locker {
public :
public :
locker ( lockee &to_lock )
void lock ();
: target ( to_lock ) {
void unlock ();
target.lock ();
}
...
~locker () {
}
target.unlock ();
resource shared ;
}
private :
mutex quard ;
lockee & target ;
guard.lock ();
};
.... // use shared  Exception!
{
guard.unlock ();
locker <mutex > critical ( guard );
... // use shared
} // destructor called
7/17/2015
CSCE 606 OO Design Patterns
55
Language Specificity of RAII
• Not directly expressible in several other OO
languages
• E.g., no destructors in Java, and unclear if and
when Java’s finalizers are executed
• OTOH, Java has its finally construct to handle both
normal and exceptional control flows
try {
// resources acquired
actions ();
} finally {
// resources released
}
7/17/2015
CSCE 606 OO Design Patterns
56
Outline
• Context
• Some key concepts and notions of OO
• Design patterns
• A few more design patterns
• Idioms
• Summary
7/17/2015
CSCE 606 OO Design Patterns
57
Meta-Taxonomy of Patterns
Type
Description
Examples
Idioms
Small scale, language/ tool/system specific
RAII. Scoped
locking.
Design patterns
Static and dynamic roles and relationships
in oft-occurring designs.
Bridge. Composite.
Visitor.
Architectural patterns
Structural organization of software
systems. Set of predefined subsystems
and their relationships. Rules and
guidelines for organizing the relationships
between them.
PublisherSubscriber.
Pipes and Filters.
Optimization principles
Avoid common design/ implementation
mistakes that degrade performance
Optimize for
common case.
Antipatterns
Commonly used pattern that is
counterproductive
Lava Flow. Copy
and Paste.
Code smells
Characterizations of suspicious code.
Similar to antipatterns, but less formal
Long Method.
Indecent Exposure.
7/17/2015
CSCE 606 OO Design Patterns
58
Are design pattern something
fundamentally different from
what existed before?
• B. Meyer: new ideas are often met with a sequence of three
reactions:
1. There is nothing to it
2. It will never work
3. That is how we have always done it
• Relating to patterns:
1. Is the notion of a design pattern a significant idea?
2. Do they really work?
3. What is new about describing solutions to problems?
• Maybe new is:
• systematic approach
• recognizing that abstractions that cannot quite be packaged into
libraries/modules can still be reusable and reused
• provides a vocabulary for discussing software development problems
7/17/2015
CSCE 606 OO Design Patterns
59
PLoP 2012
• There are devoted people: PLoP 2012: 19th
CONFERENCE ON PATTERN LANGUAGES
OF PROGRAMS
7/17/2015
CSCE 606 OO Design Patterns
60
PLoP
Pattern Languages of Programs (PLoPTM) conference is a
premier event for pattern authors and pattern enthusiasts to
gather, discuss and learn more about patterns and software
development.
The purpose of PLoP is to:
promote development of pattern languages, primarily about
aspects of software: design and programming, testing,
software architecture, user interface design, domain
modelling, and software processes. Patterns and pattern
languages for domains outside software are also welcome
7/17/2015
CSCE 606 OO Design Patterns
61
TPLoP
7/17/2015
CSCE 606 OO Design Patterns
62