Some material from R. Martin, Bruegge, Dutoit
• Context
• Some key concepts and notions of OO
• Design patterns
• A few more design patterns
• Idioms
• Summary
CSCE 431 OO Design Patterns
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
CSCE 431 OO Design Patterns
• 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
CSCE 431 OO Design Patterns
• Prepare for implementing the system model
• Transform the system model for better implementability/extensibility/performance/. . .
CSCE 431 OO Design Patterns
• 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.
CSCE 431 OO Design Patterns
• Context
• Some key concepts and notions of OO
• Design patterns
• A few more design patterns
• Idioms
• Summary
CSCE 431 OO Design Patterns
• Some principles of object-oriented programming
• About modularity
• OO twists on modularity, inheritance
• Substitutability
• Delegation
• Introduction to design patterns
• A few design patterns
CSCE 431 OO Design Patterns
• 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
CSCE 431 OO Design Patterns
• Low coupling and high cohesion
• Minimize dependencies
• Changes are localized
• Maximize unity
• Modules work well together
CSCE 431 OO Design Patterns
• 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
CSCE 431 OO Design Patterns
• 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
CSCE 431 OO Design Patterns
• 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
CSCE 431 OO Design Patterns
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
CSCE 431 OO Design Patterns
• 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
CSCE 431 OO Design Patterns
• “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
CSCE 431 OO Design Patterns
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
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 431 OO Design Patterns
}
Consider this inheritance relation:
}
Implementation inheritance vs. delegation class HashTable { class MySet { void put ( Object key , Object element ); 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 );
}
}
...
CSCE 431 OO Design Patterns
• 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
CSCE 431 OO Design Patterns
• Context
• Some key concepts and notions of OO
• Design patterns
• A few more design patterns
• Idioms
• Summary
CSCE 431 OO Design Patterns
• 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
CSCE 431 OO 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!
CSCE 431 OO Design Patterns
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
Garden to the South
Pitched Roof
Half-Hipped End
Balcony Toward the Garden
Carved Ornaments
CSCE 431 OO Design Patterns
• 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
CSCE 431 OO Design Patterns
CSCE 431 OO Design Patterns
Creational
Factory Method
Abstract Factory
Prototype
Builder
Singleton
Structural
Adapter
Façade
Proxy
Decorator
Composite
Flyweight
Bridge
CSCE 431 OO Design Patterns
Behavioral
Command
Visitor
Iterator
Interpreter
Mediator
Memento
Observer
Strategy
Template Method
Chain of Responsibility
State
Builder Separates construction from representation (how to build, e.g.,
Composite objects)
Factory method Create objects without hardcoding the class name
Abstract Factory Groups factories with a common theme
Prototype
Singleton
Cloning from prototypes
Restricts objects to no more than one instance, with a single point of access
CSCE 431 OO Design Patterns
Adapter Creates a new interface for an existing unmodifiable interface
Bridge Separates an abstraction form its implementation
Composite Tree structure of objects that allows uniform manipulation
Decorator Dynamically extensible behavior (instead of statically, as with subclassing)
Façade Unified interface to simplify use (wrap APIs, etc.)
Flyweight Share similar data among many objects
Proxy A class serving as a placeholder, possibly adding functionality, to another class
CSCE 431 OO Design Patterns
Chain of Responsibility Delegate command objects to a chain of processing objects
Command Wrap a command into an object with all the information that is needed to execute it
Interpreter How to interpret ASTs represented as Composite
Objects
Iterator
Mediator
Memento
Observer
State
Strategy
Template method
Visitor
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 431 OO Design Patterns
• 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
CSCE 431 OO Design Patterns
• 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
CSCE 431 OO Design Patterns
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.
CSCE 431 OO Design Patterns
• 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
CSCE 431 OO Design Patterns
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.
CSCE 431 OO Design Patterns
• 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
CSCE 431 OO Design Patterns
• 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.
CSCE 431 OO Design Patterns
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.
CSCE 431 OO Design Patterns
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.
CSCE 431 OO Design Patterns
• 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.
CSCE 431 OO Design 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 .
CSCE 431 OO Design Patterns
• File system implementation as discussed previously
• Graphics editors as discussed previously
CSCE 431 OO Design Patterns
• 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
CSCE 431 OO Design Patterns
• Context
• Some key concepts and notions of OO
• Design patterns
• A few more design patterns
• Idioms
• Summary
CSCE 431 OO Design Patterns
• 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.
CSCE 431 OO Design Patterns
• 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.
CSCE 431 OO Design Patterns
• 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.
CSCE 431 OO Design Patterns
• 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
CSCE 431 OO Design Patterns
CSCE 431 OO Design Patterns
CSCE 431 OO Design Patterns
• Context
• Some key concepts and notions of OO
• Design patterns
• A few more design patterns
• Idioms
• Summary
CSCE 431 OO Design Patterns
• 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 (); }
CSCE 431 OO Design Patterns
• Like design patterns, but
• Language dependent
• Usually of smaller scope
CSCE 431 OO Design Patterns
• “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
CSCE 431 OO Design Patterns
class mutex { public : void lock (); void unlock ();
...
} resource shared ; mutex quard ; guard.lock ();
.... // use shared guard.unlock ();
Exception!
guard . lock (); try
{
... // use shared
} catch (...)
{ guard.unlock (); throw ;
} guard.unlock ();
CSCE 431 OO Design Patterns
class mutex { public : void lock (); void unlock ();
...
} resource shared ; mutex quard ; guard.lock ();
.... // use shared guard.unlock ();
template < typename lockee > class locker { public : locker ( lockee &to_lock )
: target ( to_lock ) { target.lock ();
}
~locker () { target.unlock ();
} private :
};
Exception!
{ lockee & target ; locker <mutex > critical ( guard );
... // use shared
} // destructor called
CSCE 431 OO Design Patterns
• 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
}
CSCE 431 OO Design Patterns
• Context
• Some key concepts and notions of OO
• Design patterns
• A few more design patterns
• Idioms
• Summary
CSCE 431 OO Design Patterns
Type
Idioms
Design patterns
Architectural patterns
Optimization principles
Antipatterns
Code smells
Description Examples
Small scale, language/ tool/system specific RAII. Scoped locking.
Static and dynamic roles and relationships in oft-occurring designs.
Bridge. Composite.
Visitor.
Structural organization of software systems. Set of predefined subsystems and their relationships. Rules and guidelines for organizing the relationships between them.
Avoid common design/ implementation mistakes that degrade performance
Publisher-
Subscriber.
Pipes and Filters.
Optimize for common case.
Commonly used pattern that is counterproductive
Characterizations of suspicious code.
Similar to antipatterns, but less formal
Lava Flow. Copy and Paste.
Long Method.
Indecent Exposure.
CSCE 431 OO Design Patterns
• 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
CSCE 431 OO Design Patterns
• There are devoted people: PLoP 2012: 19th
CONFERENCE ON PATTERN LANGUAGES
OF PROGRAMS
CSCE 431 OO Design Patterns
Pattern Languages of Programs (PLoP TM ) 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
CSCE 431 OO Design Patterns
CSCE 431 OO Design Patterns