SlideShare a Scribd company logo
SOFTWARE PATTERNS
LINGI2252 – PROF. KIM MENS
* These slides are part of the course LINGI2252 “Software Maintenance and Evolution”,
given by Prof. Kim Mens at UCL, Belgium
*
A. PATTERNS
LINGI2252 – PROF. KIM MENS
3SOFTWARE PATTERNS – PATTERNS
WHERE DOES THE “PATTERNS” IDEA COME FROM?
Influential but controversial architect Christopher Alexander
proposed patterns as a way to reuse extensive architectural
experience
expressed as pre-canned architectural fragments
Several interesting books:
A Pattern Language: Towns, Buildings, Construction. Oxford
University Press, 1977.
The Timeless Way of Building. Oxford University Press, 1979.
3
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
Christopher Alexander
SOFTWARE PATTERNS – PATTERNS
WHAT IS A PATTERN?
4
5SOFTWARE PATTERNS – PATTERNS
EXAMPLE 1: “LIGHT ON TWO SIDES OF EVERY ROOM”
“When they have a choice, people will always gravitate to those rooms
which have light on two sides, and leave the rooms

which are lit only from one side unused and empty.
Therefore:
Locate each room so that it has outdoor space on at least two sides,
and then place windows in these outdoor walls so that natural light
falls into every room from more than one direction.”
Christopher Alexander. A Pattern Language: Towns,

Buildings, Construction. Oxford University Press, 1977.
http://www.patternlanguage.com/apl/aplsample/apl159/apl159.htm
5
6SOFTWARE PATTERNS – PATTERNS
EXAMPLE 2:“WINDOW PLACE”
6
7SOFTWARE PATTERNS – PATTERNS
ADOPTION OF CHRISTOPHER ALEXANDER’S IDEAS
Christopher Alexander's ideas were later adopted in other
disciplines
(often much more heavily than the original application of
patterns to architecture)
in particular in the software engineering community :

design patterns, architectural patterns, anti patterns, …
Keynote talk at OOPSLA 1996 on “Patterns in Architecture”
video link + keynote text
7
8SOFTWARE PATTERNS – PATTERNS
ADDITIONAL READING
▸ A.o., a good introduction to the
analogy between the work of
Christopher Alexander on patterns
in architecture and its applications
in software development.

▸ Richard P. Gabriel. Patterns of
Software: Tales from the Software
Community. Oxford University
Press, 1998. ISBN 0195121236
B. PATTERNS IN SOFTWARE
LINGI2252 – PROF. KIM MENS
10SOFTWARE PATTERNS – PATTERNS IN SOFTWARE
MANY KINDS OF PATTERNS IN SOFTWARE ENGINEERING
Best Practice Patterns
Programming Styles and Idioms
Design Patterns
Architectural Patterns
Anti Patterns
Bad Smells and Refactoring Patterns
Analysis Patterns
Organisational Patterns
Software Configuration Management Patterns
Pattern Languages of Program Design
11SOFTWARE PATTERNS – PATTERNS IN SOFTWARE
SOFTWARE DESIGN & ARCHITECTURAL PATTERNS
E. Gamma, R. Helm, R. Johnson & J. Glissades. Design
Patterns – Elements of Reusable Object-Oriented Software.
Addison-Wesley, 1995.

F. Buschmann, R. Meunier, H. Rohnert, P. Sommerlad & M.
Stal. Pattern-Oriented Software Architecture – A System of
Patterns. Wiley, 1996.

D. Schmidt, M. Stal, H. Rohnert & F. Buschmann. Pattern-
Oriented Software Architecture – Patterns for Concurrent and
Networked Objects. Wiley, 2001.
12SOFTWARE PATTERNS – PATTERNS IN SOFTWARE
WHY USE ARCHITECTURAL & DESIGN PATTERNS ?
Patterns provide guidance in the analysis & design process.
Reuse proven (design) solutions rom prior experiences.
Better structure and design, improved confidence in design.
Improve key software quality factors.
Maintainability, reusability, extensibility, … => better products.
Favour reuse at analysis, architecture & design level.
Codify “good” analyses & designs.
Disseminate know-how.
Help novices.
Encourage abstraction.
13SOFTWARE PATTERNS – PATTERNS IN SOFTWARE
WHY USE ARCHITECTURAL & DESIGN PATTERNS?
Common vocabulary
Provide explicit name for each pattern, e.g. MVC pattern.
Constitutes a common terminology; reduced complexity.
Within and across teams.
Documentation
Provide explicit representation for each pattern, preserve properties.
Effective, concise documentation.
14SOFTWARE PATTERNS – PATTERNS IN SOFTWARE
DESIGNING REUSABLE OBJECT-ORIENTED SOFTWARE IS HARD
Reusable solutions should solve a specific problem, but at the
same time be general enough to address future problems and
requirements.
Everything boils down to:
Aha-erlebnis / déjà-vu feeling
Don’t reinvent the wheel
But don’t reinvent the flat tire either ;-)
14
C. ARCHITECTURAL SOFTWARE PATTERNS
LINGI2252 – PROF. KIM MENS
16SOFTWARE PATTERNS – ARCHITECTURAL SOFTWARE PATTERNS
DESIGN AND ARCHITECTURAL PATTERNS
Document “proven” solutions to a particular design problem.
Are discovered, not invented:
Takes time to emerge, trial and error;
Requires experience;
Based on practical solutions from existing applications.
Example:
Architectural pattern: Model-View-Controller
Design patterns: Factory, Visitor, Composite, Iterator, …
16
17SOFTWARE PATTERNS – ARCHITECTURAL SOFTWARE PATTERNS
ARCHITECTURAL STYLES VS. ARCHITECTURAL PATTERNS
Idiomatic templates for software architecture fragments
Architectural style: more global
Examples: pipes-and-filters, client-server, layered
Architectural pattern: more local
Example: Model-View-Controller
A template made of pre-arranged:
modules / components
relationships / connectors
17
18SOFTWARE PATTERNS – ARCHITECTURAL SOFTWARE PATTERNS
EXAMPLE: THE MVC PATTERN (MODEL-VIEW-CONTROLLER)
Goal: uncouple application and user interaction
Applicability: any interactive application
Example:
3 main components:
model

view

controller
controller
views
model
18
19SOFTWARE PATTERNS – ARCHITECTURAL SOFTWARE PATTERNS
EXAMPLE: THE MVC PATTERN
“Model” component
provides functional core of the application
registers dependent views and controllers
notifies dependent components about data changes
19
20SOFTWARE PATTERNS – ARCHITECTURAL SOFTWARE PATTERNS
EXAMPLE: THE MVC PATTERN
“View” component
creates & initialises its associated controller
displays information to the user
retrieves data from model
implements updates for change propagation
20
21SOFTWARE PATTERNS – ARCHITECTURAL SOFTWARE PATTERNS
EXAMPLE: THE MVC PATTERN
“Controller” component
accepts user inputs as events
translates events to service requests for model or display
requests for view
implements updates for change propagation (if required)
21
22SOFTWARE PATTERNS – ARCHITECTURAL SOFTWARE PATTERNS
THE MVC PATTERN: INTERACTION PROTOCOL
 
: Model
handleEvent
: View
notifyChange
update
getData
: Controller
service
display
update
getData *
display
return
return
return
return
* to enable/disable user functions
(e.g. save when data change)
22
23SOFTWARE PATTERNS – ARCHITECTURAL SOFTWARE PATTERNS
THE MVC PATTERN: STRUCTURE
23
D. DESIGN PATTERNS
LINGI2252 – PROF. KIM MENS
Add note that this slides are largely
based on Tom’s slides.
* Slides party reused from slides by Prof. Tom Mens at UMons, Belgium
*
SOFTWARE PATTERNS – DESIGN PATTERNS
KEY REFERENCE
Design Patterns
Elements of Reusable Object-
Oriented Software
Erich Gamma

Richard Helm

Ralph Johnson

John Vlissides

(a.k.a. the “Gang of Four” or “GoF”)
Addison-Wesley, 1995

ISBN: 0-201-63361-2
25
26SOFTWARE PATTERNS – DESIGN PATTERNS
ONLINE REFERENCES
http://www.tutorialspoint.com/design_pattern/index.htm
http://www.oodesign.com/
https://sourcemaking.com/design_patterns
http://rpouiller.developpez.com/tutoriel/java/design-
patterns-gang-of-four/ (in french)
DESIGN PATTERNS ARE DESCRIPTIONS OF
COMMUNICATING OBJECTS AND CLASSES THAT
ARE CUSTOMISED TO SOLVE A GENERAL
DESIGN PROBLEM IN A PARTICULAR CONTEXT Gang of Four
Gang of Four
SOFTWARE PATTERNS – DESIGN PATTERNS 27
WHAT IS A DESIGN PATTERN?
28SOFTWARE PATTERNS – DESIGN PATTERNS
SOFTWARE DESIGN PATTERNS
Describe in a reusable way
a recurring design problem and
a best practice solution to this problem.
Are about reusing good designs and solutions
that have worked previously for similar problems.
The intent or rationale of a design pattern is a crucial part of its
definition
as well as its applicability, trade-offs, consequences, related patterns.
29SOFTWARE PATTERNS – DESIGN PATTERNS
SOFTWARE DESIGN PATTERNS
Identify participating classes and objects, their roles and
collaborations, distribution of responsibilities.
Described in an abstract way:
abstract away from concrete designs;
the way a particular design pattern is implemented may
vary.
Based on practical solutions discovered in main-stream
applications implemented in Smalltalk, Java and C++.
30SOFTWARE PATTERNS – DESIGN PATTERNS
DESIGN COVERAGE
Large portion of design covered by patterns
Most classes play role in some patterns
Improved understanding
Seductively simple to implement patterns
You still have to write functionality
Common mistake is to think design patterns solve all your
problems
31SOFTWARE PATTERNS – DESIGN PATTERNS
A FIRST EXAMPLE: THE ABSTRACT FACTORY DESIGN PATTERN
Problem
Solution
Participants
Structure
Applicability
32SOFTWARE PATTERNS – DESIGN PATTERNS
ABSTRACT FACTORY: THE PROBLEM
Entangled hierarchies
behaviour and visualisation of UI objects are combined in
same inheritance structure
Widget
Window Button Scrollbar
MSWindow MacWindow MSButton MacButton MSScrollbar MacScrollbar
33SOFTWARE PATTERNS – DESIGN PATTERNS
ABSTRACT FACTORY: THE SOLUTION
Idea of the solution
separate behaviour of UI objects from their visualisation
WidgetLook
Button ScrollbarMSLook MacLook Window
34SOFTWARE PATTERNS – DESIGN PATTERNS
ABSTRACT FACTORY: THE SOLUTION
The Abstract Factory design pattern
separate behaviour of UI objects from their visualisation
MSLook
newWindow
newButton
MacLook
newWindow
newButton
Look
newWindow
newButton
Widget
Window Button
MSWindow
MacWindow
MacButton
MSButton
35SOFTWARE PATTERNS – DESIGN PATTERNS
ABSTRACT FACTORY: PARTICIPANTS
The Abstract Factory design pattern
separate behaviour of UI objects from their visualisation
MSLook
newWindow
newButton
MacLook
newWindow
newButton
Look
newWindow
newButton
Widget
Window Button
MSWindow
MacWindow
MacButton
MSButton
ABSTRACT FACTORY
CONCRETE FACTORIES
ABSTRACT PRODUCTS
CONCRETE PRODUCTS
36SOFTWARE PATTERNS – DESIGN PATTERNS
ABSTRACT FACTORY: PARTICIPANTS
AbstractFactory (Look)
declares an interface for operations that create abstract product objects
ConcreteFactory (MSLook, MacLook)
implements the operations to create concrete product objects
AbstractProduct (Window, Button)
defines a product object to be created by the corresponding concrete factory
ConcreteProduct (MacWindow, MSButton, …)
implements the AbstractProduct interface
Client uses only interfaces declared by AbstractFactory and AbstractProduct classes
37SOFTWARE PATTERNS – DESIGN PATTERNS
ABSTRACT FACTORY: STRUCTURE
Normally a single instance of ConcreteFactory is created at run-time
AbstractFactory defers creation of product objects to its ConcreteFactory subclass
38SOFTWARE PATTERNS – DESIGN PATTERNS
ABSTRACT FACTORY: APPLICABILITY
This solution can be applied in general when
a system should be independent of how its products are
created, composed, and represented
a system should be configured with families of products
you want to provide a class library of products, and you want
to reveal just their interfaces, not their implementations
a family of related product objects is designed to be used
together, and you need to enforce this constraint
A
39SOFTWARE PATTERNS – DESIGN PATTERNS
ABSTRACT FACTORY: EVOLVABILITY (1)
Adding a new product Menu
MSLook
newWindow
newButton
MacLook
newWindow
newButton
Look
newWindow
newButton
Widget
Window Button
MSWindow
MacWindow
MacButton
MSButton
40SOFTWARE PATTERNS – DESIGN PATTERNS
ABSTRACT FACTORY: EVOLVABILITY (1)
Adding a new product Menu
MSLook
newWindow
newButton
newMenu
MacLook
newWindow
newButton
newMenu
Look
newWindow
newButton
newMenu
Widget
Window
Button
MSWindow
MacWindow
MacButton
MSButton
MacMenu
MSMenu
Menu
41SOFTWARE PATTERNS – DESIGN PATTERNS
ABSTRACT FACTORY: EVOLVABILITY (1)
Adding a new product Menu
MSLook
newWindow
newButton
newMenu
MacLook
newWindow
newButton
newMenu
Look
newWindow
newButton
newMenu
Widget
Window
Button
MSWindow
MacWindow
MacButton
MSButton
MacMenu
MSMenu
Menu
add new operation add new

product
42SOFTWARE PATTERNS – DESIGN PATTERNS
ABSTRACT FACTORY: EVOLVABILITY (2)
Adding a new concrete factory LinuxLook
MSLook
newWindow
newButton
MacLook
newWindow
newButton
Look
newWindow
newButton
Widget
Window Button
MSWindow
MacWindow
MacButton
MSButton
43SOFTWARE PATTERNS – DESIGN PATTERNS
ABSTRACT FACTORY: EVOLVABILITY (2)
Adding a new concrete factory LinuxLook
MSLook
newWindow
newButton
MacLook
newWindow
newButton
Look
newWindow
newButton
LinuxLook
newWindow
newButton
Widget
Window Button
MSWindow
MacWindow
MacButton
LinuxButton
LinuxWindow
MSButton
44SOFTWARE PATTERNS – DESIGN PATTERNS
ABSTRACT FACTORY: EVOLVABILITY (2)
Adding a new concrete factory LinuxLook
MSLook
newWindow
newButton
MacLook
newWindow
newButton
Look
newWindow
newButton
LinuxLook
newWindow
newButton
Widget
Window Button
MSWindow
MacWindow
MacButton
LinuxButton
LinuxWindow
MSButton
add new

concrete
factory
add new

concrete
products
E. SELECTED DESIGN PATTERNS
LINGI2252 – PROF. KIM MENS
* Slides party reused from slides by Prof. Tom Mens at UMons, Belgium
*
46SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS
A SELECTION OF DESIGN PATTERNS
▸ Design pattern catalogue
▸ Factory Method
▸ Template Method
▸ Strategy
▸ Observer
▸ Decorator
▸ Visitor
▸ Singleton
▸ Composite
▸ Builder
▸ Iterator
DESIGN PATTERN
CATALOGUE
48SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS
DESIGN PATTERN CATALOGUE …
Design Patterns can be classified based on two criteria:
Purpose
what a pattern does
Scope
whether the pattern applies primarily to classes or to
objects
49SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS
DESIGN PATTERN CATALOGUE : PURPOSE [GOF]
Creational design patterns
are concerned with the process of object creation
Structural design patterns
are concerned with how to compose classes and objects in
larger structures
Behavioural design patterns
are concerned with algorithms and the separation

of responsibilities between objects or classes
50SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS
DESIGN PATTERN CATALOGUE : SCOPE
Class Patterns
deal with relationships between classes (and their subclasses)
relationships are static since they are fixed at compile time
Object Patterns
deal with relationships between objects
relationships are more dynamic since they can be changed at
run-time
51SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS
DESIGN PATTERN CATALOGUE …
Purpose
Creational Structural Behavioral
Scope Class Factory Method Adapter (Class) Interpreter
Template Method
Object Abstract Factory
Builder
Prototype
Singleton
Adapter (Object)
Bridge
Composite
Decorator
Façade
Flyweight
Proxy
Chain of Responsibility
Command
Iterator
Mediator
Memento
Observer
State
Strategy
Visitor
52SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS
CREATIONAL PATTERNS
Abstract the instantiation/object creation process
Encapsulates knowledge about which concrete classes to use
Hides how class instances are created and put together
Give a lot of flexibility in what, who, how and when things get created
A creational class pattern
typically uses inheritance to vary the class to be instantiated
and delegates instantiation to another object
53SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS
STRUCTURAL PATTERNS
How to compose classes and objects to form larger structures
When/how should you use inheritance?
When/how should you use aggregation, association, composition?
A structural class pattern uses inheritance to compose interfaces or
implementation
Compositions are fixed at compile time
A structural object pattern describes ways to compose objects to realise
new functionality
Added flexibility: ability to change the composition at run-time
54SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS
BEHAVIOURAL PATTERNS
Concerned with algorithms and the assignment of responsibilities
between objects
A behavioural class pattern uses inheritance to distribute behaviour
between classes
A behavioural object pattern uses object composition rather than
inheritance
describes how groups of objects cooperate

to perform tasks no single object could carry out by itself
is concerned with encapsulating behaviour in an object

and delegating requests to it
55SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS
DESCRIPTION OF A DESIGN PATTERN
▸ Catchy name
▸ Classification
▸ Intent
▸ Also known as
▸ Motivation
▸ Applicability
▸ Structure
▸ Participants
▸ Collaboration
▸ Consequences
▸ Implementation
▸ Sample Code
▸ Known Uses
▸ Related Patterns
A DESCRIPTIVE AND UNIQUE
NAME TO HELP IDENTIFY
AND REFER TO THE PATTERN
A DESCRIPTION OF THE GOAL
BEHIND THE PATTERN AND
THE REASON FOR USING IT
OTHER NAMES FOR THE PATTERN
A SCENARIO CONSISTING OF
A PROBLEM AND A CONTEXT
IN WHICH THIS PATTERN CAN
BE USED
SITUATIONS IN WHICH THIS
PATTERN IS USABLE; THE
CONTEXT FOR THE PATTERN
GRAPHICAL REPRESENTATION OF THE PATTERN.
CLASS DIAGRAMS AND INTERACTION DIAGRAMS
CAN BE USED FOR THIS PURPOSE
LIST OF CLASSES AND
OBJECTS USED IN THE
PATTERN AND THEIR ROLES
IN THE DESIGN
HOW CLASSES AND OBJECTS
USED IN THE PATTERN
INTERACT WITH EACH OTHER
RESULTS, SIDE EFFECTS,
AND TRADE OFFS CAUSED BY
USING THE PATTERN
IMPLEMENTATION OF THE
PATTERN; THE SOLUTION
PART OF THE PATTERN
ILLUSTRATION OF HOW THE
PATTERN CAN BE USED IN A
PROGRAMMING LANGUAGE
EXAMPLES OF REAL USAGES OF THE PATTERN
OTHER PATTERNS THAT HAVE SOME RELATIONSHIP
WITH THE PATTERN; DISCUSSION OF THE DIFFERENCES
BETWEEN THE PATTERN AND SIMILAR PATTERNS
56SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS
HOW TO SELECT A DESIGN PATTERN
Study the intent section of the design pattern:

what problem does it solve?
Consider how the design patterns solves the problem
Study related patterns of similar purpose
Consider what should be variable in your design
Introduce a pattern to refactor the design
57SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS
HOW TO USE A DESIGN PATTERN
Read pattern overview for its Applicability and Consequences
Study the Structure, Participants and Collaboration sections
Look at the Sample Code
Choose names for the Participants (classes and methods)

meaningful in your context
Define the classes and appropriate interfaces
Implement the operations to carry out the responsibilities and
collaborations in the pattern
58SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS
WHEN TO USE A DESIGN PATTERN
Avoid overstructuring
Only use design patterns when there is a real need.
Introducing design patterns too early may be
counterproductive.

It makes the design structure unnecessarily complex.
Do not waste the effort of introducing a design pattern

if you are not sure that it will be needed.
59SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS
WHEN TO USE A DESIGN PATTERN
Avoid understructuring
If there is a need for design patterns, use them!
Use refactorings to introduce design patterns in existing
code.
FACTORY METHOD
SELECTED DESIGN
PATTERNS
http://www.oodesign.com/factory-method-pattern.html
61SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS
A SELECTION OF DESIGN PATTERNS
▸ Design pattern catalogue
▸ Factory Method
▸ Template Method
▸ Strategy
▸ Observer
▸ Decorator
▸ Visitor
▸ Singleton
▸ Composite
▸ Builder
▸ Iterator
62SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD
FACTORY METHOD
Classification: Class Creational.
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.
Motivating example: Application framework for handling
documents in a desktop application.
63SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD
FACTORY METHOD : MOTIVATION
Consider an application framework

for creating desktop applications.
Such applications work with documents.
The framework contains basic operations

for opening, closing and saving documents.
Specific applications (e.g., subclasses of Application) can create their own kinds of documents
(subclasses of Document)
For example, a DrawingApplication creates DrawingDocuments.
To create application-specific documents, the abstract Application class needs to delegate to its
subclasses.
Document
open():void
save(filename):void
close():void
Application
docs:Document[]
createDocument():Document

newDocument(type):void
openDocument(filename):void
public void newDocument(String type) {
Document doc = this.createDocument(type);
docs.add(doc);
doc.open();
}
64SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD
FACTORY METHOD : MOTIVATION
Document
open():void
save(filename):void
close():void
Application
docs:Document[]
createDocument():Document

newDocument(type):void
openDocument(filename):void
public void newDocument(String type) {
Document doc = this.createDocument(type);
docs.add(doc);
doc.open();
}
DrawingApplication
createDocument()
public Document createDocument() {
return new DrawingDocument()
}
DrawingDocument
open():void
save(filename):void
close():void
create
65SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD
FACTORY METHOD : APPLICABILITY
Use the Factory Method design pattern when:
A class can’t anticipate the class of objects it must create
A class wants its subclasses to specify the objects it creates
Classes delegate responsibility to one of several helper
subclasses, and you want to localise the knowledge of
which helper classes to use
66SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD
FACTORY METHOD : PARTICIPANTS
Document
open():void
save(filename):void
close():void
Application
docs:Document[]
createDocument():Document

newDocument(type):void
openDocument(filename):void
public void newDocument(String type) {
Document doc = this.createDocument(type);
docs.add(doc);
doc.open();
}
DrawingApplication
createDocument()
public Document createDocument() {
return new DrawingDocument()
}
DrawingDocument
open():void
save(filename):void
close():void
PRODUCT
CONCRETE

PRODUCT
CREATOR
CONCRETE

CREATORcreate
67SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD
FACTORY METHOD : PARTICIPANTS
Product (Document)
Defines the interface of objects the factory method creates
ConcreteProduct (DrawingDocument)
Implements the Product interface
Creator (Application)
Declares the abstract factory method (createDocument)
May call the factory method to create a Product object
ConcreteCreator (DrawingApplication)
Overrides factory method with a concrete one to return a ConcreteProduct instance
68SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD
FACTORY METHOD : STRUCTURE
Product




Creator
factoryMethod()
ConcreteCreator
factoryMethod()
ConcreteProduct
create
69SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD
FACTORY METHOD : COLLABORATIONS
Creator relies on its ConcreteCreator subclasses

to specify the concrete factory method so that it returns an
instance of the appropriate ConcreteProduct
70SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD
FACTORY METHOD: CONSEQUENCES
More reusable than creating objects directly
Connects parallel class hierarchies
Product
ConcreteProductA
Creator
factoryMethod()
ConcreteCreatorA
factoryMethod()
Client
ConcreteCreatorB
factoryMethod()
ConcreteProductB
create
create
71SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD
FACTORY METHOD: IMPLEMENTATION
Variation 1:
Some factory methods can provide a default. In that case
the factory method is not abstract. Application
docs:Document[]
createDocument():Document

newDocument(type):void
openDocument(filename):void
public Document createDocument(String type){
if (type.isEqual("drawing"))
return new DrawingDocument();
…
}
72SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD
FACTORY METHOD: IMPLEMENTATION
Variation 2:
Factory methods can be parameterised to return multiple
kinds of products.
e.g. pass an extra parameter to createDocument to specify
the kind of Document to create.
TEMPLATE
METHOD
SELECTED DESIGN
PATTERNS
74SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: TEMPLATE METHOD
A SELECTION OF DESIGN PATTERNS
▸ Design pattern catalogue
▸ Factory Method
▸ Template Method
▸ Strategy
▸ Observer
▸ Decorator
▸ Visitor
▸ Singleton
▸ Composite
▸ Builder
▸ Iterator
WILL BE DISCUSSED LATER
WHEN TALKING ABOUT
APPLICATION FRAMEWORKS
STRATEGY
SELECTED DESIGN
PATTERNS
76SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: STRATEGY
A SELECTION OF DESIGN PATTERNS
▸ Design pattern catalogue
▸ Factory Method
▸ Template Method
▸ Strategy
▸ Observer
▸ Decorator
▸ Visitor
▸ Singleton
▸ Composite
▸ Builder
▸ Iterator
77SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: STRATEGY
STRATEGY
Classification: Object Behavioural.
Intent: Define a family of algorithms, encapsulate each one,
and make them interchangeable. Strategy lets the algorithm
vary independently from clients that use it.
Motivating example:
Different sorting algorithms
String search in a text processor
78SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: STRATEGY
STRATEGY: MOTIVATION
There are common situations when classes differ only in their
behaviour. For such cases it is a good idea to isolate the
algorithms in separate classes in order to have the ability to
select different algorithms at runtime.
SearchAlgorithm2
searchFor(String, Text)
SearchAlgorithm1
searchFor(String, Text)
TextProcessor
text : Text
search(String)
79SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: STRATEGY
STRATEGY: MOTIVATION
There are common situations when classes differ only in their
behaviour. For such cases it is a good idea to isolate the
algorithms in separate classes in order to have the ability to
select different algorithms at runtime.
searcher
SearchAlgorithm
searchFor(String, Text)
SearchAlgorithm2
searchFor(String, Text)
SearchAlgorithm1
searchFor(String, Text)
TextProcessor
text : Text
search(String)
1
search(String s) {
…
searcher.searchFor(s,text)
…
}
80SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: STRATEGY
STRATEGY: APPLICABILITY
Use the Strategy design pattern when
Many related classes that differ only in their behaviour
You need different variants of an algorithm
An algorithm uses data that clients should not know about
A class defines many behaviours
81SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: STRATEGY
STRATEGY: PARTICIPANTS
Strategy (SearchAlgorithm)
Declares an interface common to all supported algorithms. Context uses this
interface to call the algorithm defined by a ConcreteStrategy
ConcreteStrategy (SearchAlgorithm1, SearchAlgorithm2)
Implements the algorithm using the Strategy interface
Context (TextProcessor)
Is configured with a ConcreteStrategy object
Maintains a reference to a Strategy object
May define an interface that lets Strategy access its data
82SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: STRATEGY
STRATEGY: STRUCTURE
Strategy
algorithmInterface()
Strategy2
algorithmInterface()
Strategy1
algorithmInterface()
Context
strategy : Strategy

contextInterface()
1
strategy
contextInterface() {
…
strategy.algorithmInterface()
…
}
83SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: STRATEGY
STRATEGY: COLLABORATIONS
Strategy and Context interact to implement the chosen algorithm
Context may pass all data required by the algorithm to the
strategy when the algorithm is called
Context can pass itself as an argument to Strategy operations
A Context forwards requests from its clients to its strategy
Clients usually create and pass a ConcreteStrategy object to
the Context. From then on, they interact with the Context
exclusively.
84SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: STRATEGY
STRATEGY: CONSEQUENCES
Families of related algorithms
An alternative to subclassing
Strategies eliminate conditionals
Provide a choice of implementation
allow for different implementations of same behaviour
Overhead involved
Communication between Context and Strategy
Increased number of objects
85SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: STRATEGY
STRATEGY: IMPLEMENTATION
The Strategy interface must provide enough information to
ConcreteStrategy
Default behaviour can be incorporated in the Context object.
If no strategy object is present, this default behaviour can be
used.
DECORATOR
SELECTED DESIGN
PATTERNS
87SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: DECORATOR
A SELECTION OF DESIGN PATTERNS
▸ Design pattern catalogue
▸ Factory Method
▸ Template Method
▸ Strategy
▸ Observer
▸ Decorator
▸ Visitor
▸ Singleton
▸ Composite
▸ Builder
▸ Iterator
88SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: DECORATOR
DECORATOR
Classification: Object Structural.
Intent:
Attach additional responsibilities to an object dynamically.
Decorators provide a dynamic alternative for subclassing.
Motivating example:
Adding borders/scrollbars/… to a visual component
89SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: DECORATOR
DECORATOR: MOTIVATION
Traditional solution impractical
when I want to apply different
decorations to a same component
when I want to apply a same
decoration to different components
VisualComponent
draw()
TextViewWithBorder
draw()
drawBorder()
TextViewWithScrollBar
draw()
scrollTo()
draw() {
super.draw();
drawBorder()
}
TextView
draw()
90SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: DECORATOR
DECORATOR: MOTIVATION
component
VisualComponent
draw()
TextView
draw()
Decorator
draw()
BorderDecorator
draw()
drawBorder()
ScrollDecorator
draw()
scrollTo()
1
draw() {
…
component.draw()
…
}
draw() {
super.draw();
drawBorder()
}
Solution with decorator

design pattern
91SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: DECORATOR
DECORATOR: APPLICABILITY
Use the Decorator design pattern
To add responsibilities to individual objects dynamically
and transparently without affecting other objects
For responsibilities that can be withdrawn
When extending by subclassing is impractical
92SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: DECORATOR
DECORATOR: PARTICIPANTS
Component (VisualComponent)
Defines the interface for objects that can have responsibilities added to them
dynamically
ConcreteComponent (TextView)
Defines an object to which we want to attach additional responsibilities
Decorator (Decorator)
Maintains a reference to a Component object and defines an interface that
conforms to the Components interface
ConcreteDecorator (BorderDecorator)
Adds responsibilities to the component
93SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: DECORATOR
DECORATOR: MOTIVATION
component
Component
operation()
ConcreteComponent
operation()
Decorator
operation()
ConcreteDecoratorB
added state
operation()
ConcreteDecoratorA
added state
operation()
1
operation() {
…
component.operation()
…
}
operation() {
super.operation();
…added behaviour…
}
94SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: DECORATOR
DECORATOR: COLLABORATIONS
Decorator forwards requests to the Component object. It
may optionally perform additional behaviour before and
after forwarding the request
95SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: DECORATOR
DECORATOR: CONSEQUENCES
More flexible than static inheritance
Possible to dynamically add or withdraw responsibilities
Avoids classes with a lot of features
Lots of little objects
96SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: DECORATOR
DECORATOR: IMPLEMENTATION
Object identity can be a problem
a decorated component is not identical to the object itself
COMPOSITE
SELECTED DESIGN
PATTERNS
F. ANTIPATTERNS
LINGI2252 – PROF. KIM MENS
* Slides party reused from slides by Prof. Tom Mens at UMons, Belgium
*
SOFTWARE PATTERNS – ANTI PATTERNS
KEY REFERENCE
Anti Patterns
Refactoring Software, Architectures
and Projects in Crisis
W. J. Brown

R. C. Malveau

H. W. McCormick

T.J. Mowbray

John Wiley & Sons, 1997
99
100SOFTWARE PATTERNS – ANTI PATTERNS
WHAT ARE ANTIPATTERNS?
Design patterns identify good working practices
Anti patterns identify common mistakes and how these
mistakes can be overcome in refactored solutions.
An AntiPattern is
“a commonly used solution to a problem that generates
decidedly negative consequences”
101SOFTWARE PATTERNS – ANTI PATTERNS
WHAT ARE ANTIPATTERNS?
An AntiPattern is a special (negative) design pattern

which features an extra refactored solution to the problem.
Context
Forces
Problem
Solution
Pattern
Context
Forces
Problem
Negative Solution
AntiPattern
Problem
Refactored Solution
102SOFTWARE PATTERNS – ANTI PATTERNS
7 DEADLY SINS
1. Haste : Hasty decisions lead to compromises in software
quality. Especially testing is a victim.
“Just clean up the code, we ship tomorrow…”
2. Apathy : Not caring about solving known problems
“Reuse? Who’s ever gonna reuse this crappy code?”
3. Narrow-mindedness : Refusal to practice solutions that are
widely known to be effective.
“I don’t need to know, and… I don’t care to know”
103SOFTWARE PATTERNS – ANTI PATTERNS
7 DEADLY SINS
4. Sloth (lazyness) : Making poor decisions based upon easy
answers (lazy developers)
5. Avarice (greed) : The modeling of excessive details, resulting
in overcomplexity due to insufficient abstraction
“I’m impressed ! The most complex model ever done !”
6. Ignorance : Failing to seek understanding
“100 pages… let’s find a one page summary on the net”
7. Pride : Reinventing designs instead of reusing them.
104SOFTWARE PATTERNS – ANTI PATTERNS
CATEGORIES OF ANTIPATTERNS
Development AntiPatterns
technical problems/solutions encountered by programmers
Architectural AntiPatterns
identification of common problems in system structures
Managerial AntiPatterns
addresses common problems in software processes and
development organisations
105SOFTWARE PATTERNS – ANTI PATTERNS
DEVELOPMENT ANTIPATTERNS
The Blob
Continuous Obsolescence
Lava Flow
Ambiguous Viewpoint
Functional Decomposition
Poltergeists
Golden Hammer
Boat Anchor
Dead End
Spaghetti Code
Minefield Walking
Cut-and-Paste
106SOFTWARE PATTERNS – ANTI PATTERNS
EXAMPLE: THE BLOB
Category : Software Development
Also Known As : The God Class
Scale : Application
Refactored Solution Name : Refactoring of Responsibilities
Root Causes : Sloth, Haste
107SOFTWARE PATTERNS – ANTI PATTERNS
THE BLOB: GENERAL FORM
Designs where one class monopolises the processing, and
other classes primarily encapsulate data
Key problem: majority of responsibilities allocated to a
single class.
In general it is a kind of procedural design
conflicts with OO paradigm
108SOFTWARE PATTERNS – ANTI PATTERNS
THE BLOB: REFACTORED SOLUTION
Identify or categorise related attributes and operations
Look for ‘natural homes’ for these collections of functionality
Apply OO design techniques (e.g., inheritance, …)
Apply refactorings to bring code back in shape
G. CONCLUSION
LINGI2252 – PROF. KIM MENS
110SOFTWARE PATTERNS – CONCLUSION
SOFTWARE PATTERNS …
capture successful solutions to recurring problems that arise
during software construction
define a common vocabulary amongst software developers
increase reuse of design as opposed to reuse of
implementation
help to improve software quality
can be introduced by refactoring
should be used with care! (anti patterns)
111SOFTWARE PATTERNS – CONCLUSION
ARCHITECTURAL AND DESIGN PATTERNS ARE
Smart
provide elegant solutions that a novice would not think of
Generic
independent of a specific system or programming language
Well-proven
successfully tested and applied in several real-world
applications
Software Patterns
113SOFTWARE PATTERNS – QUESTIONS
POSSIBLE QUESTIONS (1)
▸ What do Christopher Alexander’s (building) architectural patterns and
(software) design patterns have in common? Explain with a concrete example.
▸ Give a definition of the notion of “design pattern”.
▸ What are design patterns good for and why? Why cannot you say “I have
invented a design pattern”?
▸ Explain the different parts of which a design pattern description typically
exists.
▸ (Catchy name, Classification, Intent, Also known as, Motivation,
Applicability, Structure, Participants, Collaboration, Consequences,
Implementation, Sample Code, Known Uses, Related Patterns)
114SOFTWARE PATTERNS – QUESTIONS
POSSIBLE QUESTIONS (2)
▸ Explain and illustrate the Abstract Factory design pattern in detail. Clearly
mention its problem, solution, participants, structure and applicability.
▸ Explain the Factory Method design pattern in detail. Clearly mention its
Intent, Motivation, Applicability, Participants, Collaboration, Consequences
and Implementation.
▸ Same question for the Strategy and Decorator design patterns.
▸ What is an antipattern and how does it compare to a design pattern? What
purpose does it serve?
▸ Explain at least 4 of the 7 deadly sins related to antipatterns.
▸ Explain The Blob antipattern.

More Related Content

PPT
PPTX
Ch2 sw processes
PPTX
03 - Agile Software Development.pptx
PPTX
Design Pattern in Software Engineering
PDF
Software Maintenance and Evolution
PPT
PPTX
Ch7 implementation
PDF
3. ch 2-process model
Ch2 sw processes
03 - Agile Software Development.pptx
Design Pattern in Software Engineering
Software Maintenance and Evolution
Ch7 implementation
3. ch 2-process model

What's hot (20)

PPTX
Ch23-Software Engineering 9
PPTX
V model software engineering
DOCX
Software engineering project(srs)!!
PPTX
Activity Diagram Examples by Creately
PDF
SE_Lec 12_ Project Planning
PPTX
Ch3. agile sw dev
PPT
extreme Programming
PPTX
Final Year Project Presentation Android base Book Store
PDF
Software Requirements Specification (SRS) for Online Tower Plotting System (O...
PPTX
PROTOTYPE MODEL
DOCX
Vehicle Tracking System Android Project Report
PPT
Ooad overview
DOCX
Final srs of academic a webpage based android app
DOCX
Incremental Model
PPTX
Fundamental software engineering activities
PPT
Design patterns ppt
PPT
Requirement specification (SRS)
PPTX
Creational pattern
PDF
A project report on chat application
PPT
System Models in Software Engineering SE7
Ch23-Software Engineering 9
V model software engineering
Software engineering project(srs)!!
Activity Diagram Examples by Creately
SE_Lec 12_ Project Planning
Ch3. agile sw dev
extreme Programming
Final Year Project Presentation Android base Book Store
Software Requirements Specification (SRS) for Online Tower Plotting System (O...
PROTOTYPE MODEL
Vehicle Tracking System Android Project Report
Ooad overview
Final srs of academic a webpage based android app
Incremental Model
Fundamental software engineering activities
Design patterns ppt
Requirement specification (SRS)
Creational pattern
A project report on chat application
System Models in Software Engineering SE7
Ad

Similar to Software Patterns (20)

PPT
CS6201 Software Reuse - Design Patterns
PPT
Class (1)
PPT
Introduction to design patterns
PPTX
Cs 1023 lec 9 design pattern (week 2)
PDF
Patterns Overview
PPTX
Refactoring to Design Patterns
PDF
Cse 6007 fall2012
PPTX
Design Patterns - General Introduction
PDF
Discovering patterns
PDF
Ptidej Architecture, Design, and Implementation in Action v2.1
PPTX
sample Pattern Design explaine .pptx
PDF
Module 2 design patterns-2
PDF
130607 yann-gael gueheneuc - ptidej tool suite
PDF
Design Patterns Elements of Reusable Object (download tai tailieutuoi.com).pdf
PDF
Design Patterns Elements of Reusable Object-Oriented Software
PPT
Chapter 12
PPTX
Design Patterns- Course for students .pptx
PPTX
PDF
Design pattern
PPTX
design pattern is the computer scicence subject
CS6201 Software Reuse - Design Patterns
Class (1)
Introduction to design patterns
Cs 1023 lec 9 design pattern (week 2)
Patterns Overview
Refactoring to Design Patterns
Cse 6007 fall2012
Design Patterns - General Introduction
Discovering patterns
Ptidej Architecture, Design, and Implementation in Action v2.1
sample Pattern Design explaine .pptx
Module 2 design patterns-2
130607 yann-gael gueheneuc - ptidej tool suite
Design Patterns Elements of Reusable Object (download tai tailieutuoi.com).pdf
Design Patterns Elements of Reusable Object-Oriented Software
Chapter 12
Design Patterns- Course for students .pptx
Design pattern
design pattern is the computer scicence subject
Ad

More from kim.mens (20)

PDF
Context-Oriented Programming
PDF
Software Reuse and Object-Oriented Programming
PDF
Bad Code Smells
PDF
Object-Oriented Design Heuristics
PDF
Code Refactoring
PDF
Domain Modelling
PDF
Object-Oriented Application Frameworks
PDF
Towards a Context-Oriented Software Implementation Framework
PDF
Towards a Taxonomy of Context-Aware Software Variabilty Approaches
PDF
Breaking the Walls: A Unified Vision on Context-Oriented Software Engineering
PDF
Context-oriented programming
PDF
Basics of reflection
PDF
Advanced Reflection in Java
PDF
Basics of reflection in java
PDF
Reflection in Ruby
PDF
Introduction to Ruby
PDF
Introduction to Smalltalk
PDF
A gentle introduction to reflection
PDF
Managing the Evolution of Information Systems with Intensional Views and Rela...
PDF
Usage contracts (presented at SATToSE 2014 in L'Aquila, Italy)
Context-Oriented Programming
Software Reuse and Object-Oriented Programming
Bad Code Smells
Object-Oriented Design Heuristics
Code Refactoring
Domain Modelling
Object-Oriented Application Frameworks
Towards a Context-Oriented Software Implementation Framework
Towards a Taxonomy of Context-Aware Software Variabilty Approaches
Breaking the Walls: A Unified Vision on Context-Oriented Software Engineering
Context-oriented programming
Basics of reflection
Advanced Reflection in Java
Basics of reflection in java
Reflection in Ruby
Introduction to Ruby
Introduction to Smalltalk
A gentle introduction to reflection
Managing the Evolution of Information Systems with Intensional Views and Rela...
Usage contracts (presented at SATToSE 2014 in L'Aquila, Italy)

Recently uploaded (20)

PDF
RMMM.pdf make it easy to upload and study
PDF
Classroom Observation Tools for Teachers
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Computing-Curriculum for Schools in Ghana
PPTX
GDM (1) (1).pptx small presentation for students
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Cell Types and Its function , kingdom of life
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Sports Quiz easy sports quiz sports quiz
RMMM.pdf make it easy to upload and study
Classroom Observation Tools for Teachers
O7-L3 Supply Chain Operations - ICLT Program
PPH.pptx obstetrics and gynecology in nursing
Module 4: Burden of Disease Tutorial Slides S2 2025
Computing-Curriculum for Schools in Ghana
GDM (1) (1).pptx small presentation for students
Microbial disease of the cardiovascular and lymphatic systems
human mycosis Human fungal infections are called human mycosis..pptx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Cell Types and Its function , kingdom of life
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
01-Introduction-to-Information-Management.pdf
Cell Structure & Organelles in detailed.
TR - Agricultural Crops Production NC III.pdf
Renaissance Architecture: A Journey from Faith to Humanism
Sports Quiz easy sports quiz sports quiz

Software Patterns

  • 1. SOFTWARE PATTERNS LINGI2252 – PROF. KIM MENS * These slides are part of the course LINGI2252 “Software Maintenance and Evolution”, given by Prof. Kim Mens at UCL, Belgium *
  • 2. A. PATTERNS LINGI2252 – PROF. KIM MENS
  • 3. 3SOFTWARE PATTERNS – PATTERNS WHERE DOES THE “PATTERNS” IDEA COME FROM? Influential but controversial architect Christopher Alexander proposed patterns as a way to reuse extensive architectural experience expressed as pre-canned architectural fragments Several interesting books: A Pattern Language: Towns, Buildings, Construction. Oxford University Press, 1977. The Timeless Way of Building. Oxford University Press, 1979. 3
  • 4. 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 Christopher Alexander SOFTWARE PATTERNS – PATTERNS WHAT IS A PATTERN? 4
  • 5. 5SOFTWARE PATTERNS – PATTERNS EXAMPLE 1: “LIGHT ON TWO SIDES OF EVERY ROOM” “When they have a choice, people will always gravitate to those rooms which have light on two sides, and leave the rooms
 which are lit only from one side unused and empty. Therefore: Locate each room so that it has outdoor space on at least two sides, and then place windows in these outdoor walls so that natural light falls into every room from more than one direction.” Christopher Alexander. A Pattern Language: Towns,
 Buildings, Construction. Oxford University Press, 1977. http://www.patternlanguage.com/apl/aplsample/apl159/apl159.htm 5
  • 6. 6SOFTWARE PATTERNS – PATTERNS EXAMPLE 2:“WINDOW PLACE” 6
  • 7. 7SOFTWARE PATTERNS – PATTERNS ADOPTION OF CHRISTOPHER ALEXANDER’S IDEAS Christopher Alexander's ideas were later adopted in other disciplines (often much more heavily than the original application of patterns to architecture) in particular in the software engineering community :
 design patterns, architectural patterns, anti patterns, … Keynote talk at OOPSLA 1996 on “Patterns in Architecture” video link + keynote text 7
  • 8. 8SOFTWARE PATTERNS – PATTERNS ADDITIONAL READING ▸ A.o., a good introduction to the analogy between the work of Christopher Alexander on patterns in architecture and its applications in software development.
 ▸ Richard P. Gabriel. Patterns of Software: Tales from the Software Community. Oxford University Press, 1998. ISBN 0195121236
  • 9. B. PATTERNS IN SOFTWARE LINGI2252 – PROF. KIM MENS
  • 10. 10SOFTWARE PATTERNS – PATTERNS IN SOFTWARE MANY KINDS OF PATTERNS IN SOFTWARE ENGINEERING Best Practice Patterns Programming Styles and Idioms Design Patterns Architectural Patterns Anti Patterns Bad Smells and Refactoring Patterns Analysis Patterns Organisational Patterns Software Configuration Management Patterns Pattern Languages of Program Design
  • 11. 11SOFTWARE PATTERNS – PATTERNS IN SOFTWARE SOFTWARE DESIGN & ARCHITECTURAL PATTERNS E. Gamma, R. Helm, R. Johnson & J. Glissades. Design Patterns – Elements of Reusable Object-Oriented Software. Addison-Wesley, 1995.
 F. Buschmann, R. Meunier, H. Rohnert, P. Sommerlad & M. Stal. Pattern-Oriented Software Architecture – A System of Patterns. Wiley, 1996.
 D. Schmidt, M. Stal, H. Rohnert & F. Buschmann. Pattern- Oriented Software Architecture – Patterns for Concurrent and Networked Objects. Wiley, 2001.
  • 12. 12SOFTWARE PATTERNS – PATTERNS IN SOFTWARE WHY USE ARCHITECTURAL & DESIGN PATTERNS ? Patterns provide guidance in the analysis & design process. Reuse proven (design) solutions rom prior experiences. Better structure and design, improved confidence in design. Improve key software quality factors. Maintainability, reusability, extensibility, … => better products. Favour reuse at analysis, architecture & design level. Codify “good” analyses & designs. Disseminate know-how. Help novices. Encourage abstraction.
  • 13. 13SOFTWARE PATTERNS – PATTERNS IN SOFTWARE WHY USE ARCHITECTURAL & DESIGN PATTERNS? Common vocabulary Provide explicit name for each pattern, e.g. MVC pattern. Constitutes a common terminology; reduced complexity. Within and across teams. Documentation Provide explicit representation for each pattern, preserve properties. Effective, concise documentation.
  • 14. 14SOFTWARE PATTERNS – PATTERNS IN SOFTWARE DESIGNING REUSABLE OBJECT-ORIENTED SOFTWARE IS HARD Reusable solutions should solve a specific problem, but at the same time be general enough to address future problems and requirements. Everything boils down to: Aha-erlebnis / déjà-vu feeling Don’t reinvent the wheel But don’t reinvent the flat tire either ;-) 14
  • 15. C. ARCHITECTURAL SOFTWARE PATTERNS LINGI2252 – PROF. KIM MENS
  • 16. 16SOFTWARE PATTERNS – ARCHITECTURAL SOFTWARE PATTERNS DESIGN AND ARCHITECTURAL PATTERNS Document “proven” solutions to a particular design problem. Are discovered, not invented: Takes time to emerge, trial and error; Requires experience; Based on practical solutions from existing applications. Example: Architectural pattern: Model-View-Controller Design patterns: Factory, Visitor, Composite, Iterator, … 16
  • 17. 17SOFTWARE PATTERNS – ARCHITECTURAL SOFTWARE PATTERNS ARCHITECTURAL STYLES VS. ARCHITECTURAL PATTERNS Idiomatic templates for software architecture fragments Architectural style: more global Examples: pipes-and-filters, client-server, layered Architectural pattern: more local Example: Model-View-Controller A template made of pre-arranged: modules / components relationships / connectors 17
  • 18. 18SOFTWARE PATTERNS – ARCHITECTURAL SOFTWARE PATTERNS EXAMPLE: THE MVC PATTERN (MODEL-VIEW-CONTROLLER) Goal: uncouple application and user interaction Applicability: any interactive application Example: 3 main components: model
 view
 controller controller views model 18
  • 19. 19SOFTWARE PATTERNS – ARCHITECTURAL SOFTWARE PATTERNS EXAMPLE: THE MVC PATTERN “Model” component provides functional core of the application registers dependent views and controllers notifies dependent components about data changes 19
  • 20. 20SOFTWARE PATTERNS – ARCHITECTURAL SOFTWARE PATTERNS EXAMPLE: THE MVC PATTERN “View” component creates & initialises its associated controller displays information to the user retrieves data from model implements updates for change propagation 20
  • 21. 21SOFTWARE PATTERNS – ARCHITECTURAL SOFTWARE PATTERNS EXAMPLE: THE MVC PATTERN “Controller” component accepts user inputs as events translates events to service requests for model or display requests for view implements updates for change propagation (if required) 21
  • 22. 22SOFTWARE PATTERNS – ARCHITECTURAL SOFTWARE PATTERNS THE MVC PATTERN: INTERACTION PROTOCOL   : Model handleEvent : View notifyChange update getData : Controller service display update getData * display return return return return * to enable/disable user functions (e.g. save when data change) 22
  • 23. 23SOFTWARE PATTERNS – ARCHITECTURAL SOFTWARE PATTERNS THE MVC PATTERN: STRUCTURE 23
  • 24. D. DESIGN PATTERNS LINGI2252 – PROF. KIM MENS Add note that this slides are largely based on Tom’s slides. * Slides party reused from slides by Prof. Tom Mens at UMons, Belgium *
  • 25. SOFTWARE PATTERNS – DESIGN PATTERNS KEY REFERENCE Design Patterns Elements of Reusable Object- Oriented Software Erich Gamma
 Richard Helm
 Ralph Johnson
 John Vlissides
 (a.k.a. the “Gang of Four” or “GoF”) Addison-Wesley, 1995
 ISBN: 0-201-63361-2 25
  • 26. 26SOFTWARE PATTERNS – DESIGN PATTERNS ONLINE REFERENCES http://www.tutorialspoint.com/design_pattern/index.htm http://www.oodesign.com/ https://sourcemaking.com/design_patterns http://rpouiller.developpez.com/tutoriel/java/design- patterns-gang-of-four/ (in french)
  • 27. DESIGN PATTERNS ARE DESCRIPTIONS OF COMMUNICATING OBJECTS AND CLASSES THAT ARE CUSTOMISED TO SOLVE A GENERAL DESIGN PROBLEM IN A PARTICULAR CONTEXT Gang of Four Gang of Four SOFTWARE PATTERNS – DESIGN PATTERNS 27 WHAT IS A DESIGN PATTERN?
  • 28. 28SOFTWARE PATTERNS – DESIGN PATTERNS SOFTWARE DESIGN PATTERNS Describe in a reusable way a recurring design problem and a best practice solution to this problem. Are about reusing good designs and solutions that have worked previously for similar problems. The intent or rationale of a design pattern is a crucial part of its definition as well as its applicability, trade-offs, consequences, related patterns.
  • 29. 29SOFTWARE PATTERNS – DESIGN PATTERNS SOFTWARE DESIGN PATTERNS Identify participating classes and objects, their roles and collaborations, distribution of responsibilities. Described in an abstract way: abstract away from concrete designs; the way a particular design pattern is implemented may vary. Based on practical solutions discovered in main-stream applications implemented in Smalltalk, Java and C++.
  • 30. 30SOFTWARE PATTERNS – DESIGN PATTERNS DESIGN COVERAGE Large portion of design covered by patterns Most classes play role in some patterns Improved understanding Seductively simple to implement patterns You still have to write functionality Common mistake is to think design patterns solve all your problems
  • 31. 31SOFTWARE PATTERNS – DESIGN PATTERNS A FIRST EXAMPLE: THE ABSTRACT FACTORY DESIGN PATTERN Problem Solution Participants Structure Applicability
  • 32. 32SOFTWARE PATTERNS – DESIGN PATTERNS ABSTRACT FACTORY: THE PROBLEM Entangled hierarchies behaviour and visualisation of UI objects are combined in same inheritance structure Widget Window Button Scrollbar MSWindow MacWindow MSButton MacButton MSScrollbar MacScrollbar
  • 33. 33SOFTWARE PATTERNS – DESIGN PATTERNS ABSTRACT FACTORY: THE SOLUTION Idea of the solution separate behaviour of UI objects from their visualisation WidgetLook Button ScrollbarMSLook MacLook Window
  • 34. 34SOFTWARE PATTERNS – DESIGN PATTERNS ABSTRACT FACTORY: THE SOLUTION The Abstract Factory design pattern separate behaviour of UI objects from their visualisation MSLook newWindow newButton MacLook newWindow newButton Look newWindow newButton Widget Window Button MSWindow MacWindow MacButton MSButton
  • 35. 35SOFTWARE PATTERNS – DESIGN PATTERNS ABSTRACT FACTORY: PARTICIPANTS The Abstract Factory design pattern separate behaviour of UI objects from their visualisation MSLook newWindow newButton MacLook newWindow newButton Look newWindow newButton Widget Window Button MSWindow MacWindow MacButton MSButton ABSTRACT FACTORY CONCRETE FACTORIES ABSTRACT PRODUCTS CONCRETE PRODUCTS
  • 36. 36SOFTWARE PATTERNS – DESIGN PATTERNS ABSTRACT FACTORY: PARTICIPANTS AbstractFactory (Look) declares an interface for operations that create abstract product objects ConcreteFactory (MSLook, MacLook) implements the operations to create concrete product objects AbstractProduct (Window, Button) defines a product object to be created by the corresponding concrete factory ConcreteProduct (MacWindow, MSButton, …) implements the AbstractProduct interface Client uses only interfaces declared by AbstractFactory and AbstractProduct classes
  • 37. 37SOFTWARE PATTERNS – DESIGN PATTERNS ABSTRACT FACTORY: STRUCTURE Normally a single instance of ConcreteFactory is created at run-time AbstractFactory defers creation of product objects to its ConcreteFactory subclass
  • 38. 38SOFTWARE PATTERNS – DESIGN PATTERNS ABSTRACT FACTORY: APPLICABILITY This solution can be applied in general when a system should be independent of how its products are created, composed, and represented a system should be configured with families of products you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations a family of related product objects is designed to be used together, and you need to enforce this constraint A
  • 39. 39SOFTWARE PATTERNS – DESIGN PATTERNS ABSTRACT FACTORY: EVOLVABILITY (1) Adding a new product Menu MSLook newWindow newButton MacLook newWindow newButton Look newWindow newButton Widget Window Button MSWindow MacWindow MacButton MSButton
  • 40. 40SOFTWARE PATTERNS – DESIGN PATTERNS ABSTRACT FACTORY: EVOLVABILITY (1) Adding a new product Menu MSLook newWindow newButton newMenu MacLook newWindow newButton newMenu Look newWindow newButton newMenu Widget Window Button MSWindow MacWindow MacButton MSButton MacMenu MSMenu Menu
  • 41. 41SOFTWARE PATTERNS – DESIGN PATTERNS ABSTRACT FACTORY: EVOLVABILITY (1) Adding a new product Menu MSLook newWindow newButton newMenu MacLook newWindow newButton newMenu Look newWindow newButton newMenu Widget Window Button MSWindow MacWindow MacButton MSButton MacMenu MSMenu Menu add new operation add new
 product
  • 42. 42SOFTWARE PATTERNS – DESIGN PATTERNS ABSTRACT FACTORY: EVOLVABILITY (2) Adding a new concrete factory LinuxLook MSLook newWindow newButton MacLook newWindow newButton Look newWindow newButton Widget Window Button MSWindow MacWindow MacButton MSButton
  • 43. 43SOFTWARE PATTERNS – DESIGN PATTERNS ABSTRACT FACTORY: EVOLVABILITY (2) Adding a new concrete factory LinuxLook MSLook newWindow newButton MacLook newWindow newButton Look newWindow newButton LinuxLook newWindow newButton Widget Window Button MSWindow MacWindow MacButton LinuxButton LinuxWindow MSButton
  • 44. 44SOFTWARE PATTERNS – DESIGN PATTERNS ABSTRACT FACTORY: EVOLVABILITY (2) Adding a new concrete factory LinuxLook MSLook newWindow newButton MacLook newWindow newButton Look newWindow newButton LinuxLook newWindow newButton Widget Window Button MSWindow MacWindow MacButton LinuxButton LinuxWindow MSButton add new
 concrete factory add new
 concrete products
  • 45. E. SELECTED DESIGN PATTERNS LINGI2252 – PROF. KIM MENS * Slides party reused from slides by Prof. Tom Mens at UMons, Belgium *
  • 46. 46SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS A SELECTION OF DESIGN PATTERNS ▸ Design pattern catalogue ▸ Factory Method ▸ Template Method ▸ Strategy ▸ Observer ▸ Decorator ▸ Visitor ▸ Singleton ▸ Composite ▸ Builder ▸ Iterator
  • 48. 48SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS DESIGN PATTERN CATALOGUE … Design Patterns can be classified based on two criteria: Purpose what a pattern does Scope whether the pattern applies primarily to classes or to objects
  • 49. 49SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS DESIGN PATTERN CATALOGUE : PURPOSE [GOF] Creational design patterns are concerned with the process of object creation Structural design patterns are concerned with how to compose classes and objects in larger structures Behavioural design patterns are concerned with algorithms and the separation
 of responsibilities between objects or classes
  • 50. 50SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS DESIGN PATTERN CATALOGUE : SCOPE Class Patterns deal with relationships between classes (and their subclasses) relationships are static since they are fixed at compile time Object Patterns deal with relationships between objects relationships are more dynamic since they can be changed at run-time
  • 51. 51SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS DESIGN PATTERN CATALOGUE … Purpose Creational Structural Behavioral Scope Class Factory Method Adapter (Class) Interpreter Template Method Object Abstract Factory Builder Prototype Singleton Adapter (Object) Bridge Composite Decorator Façade Flyweight Proxy Chain of Responsibility Command Iterator Mediator Memento Observer State Strategy Visitor
  • 52. 52SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS CREATIONAL PATTERNS Abstract the instantiation/object creation process Encapsulates knowledge about which concrete classes to use Hides how class instances are created and put together Give a lot of flexibility in what, who, how and when things get created A creational class pattern typically uses inheritance to vary the class to be instantiated and delegates instantiation to another object
  • 53. 53SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS STRUCTURAL PATTERNS How to compose classes and objects to form larger structures When/how should you use inheritance? When/how should you use aggregation, association, composition? A structural class pattern uses inheritance to compose interfaces or implementation Compositions are fixed at compile time A structural object pattern describes ways to compose objects to realise new functionality Added flexibility: ability to change the composition at run-time
  • 54. 54SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS BEHAVIOURAL PATTERNS Concerned with algorithms and the assignment of responsibilities between objects A behavioural class pattern uses inheritance to distribute behaviour between classes A behavioural object pattern uses object composition rather than inheritance describes how groups of objects cooperate
 to perform tasks no single object could carry out by itself is concerned with encapsulating behaviour in an object
 and delegating requests to it
  • 55. 55SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS DESCRIPTION OF A DESIGN PATTERN ▸ Catchy name ▸ Classification ▸ Intent ▸ Also known as ▸ Motivation ▸ Applicability ▸ Structure ▸ Participants ▸ Collaboration ▸ Consequences ▸ Implementation ▸ Sample Code ▸ Known Uses ▸ Related Patterns A DESCRIPTIVE AND UNIQUE NAME TO HELP IDENTIFY AND REFER TO THE PATTERN A DESCRIPTION OF THE GOAL BEHIND THE PATTERN AND THE REASON FOR USING IT OTHER NAMES FOR THE PATTERN A SCENARIO CONSISTING OF A PROBLEM AND A CONTEXT IN WHICH THIS PATTERN CAN BE USED SITUATIONS IN WHICH THIS PATTERN IS USABLE; THE CONTEXT FOR THE PATTERN GRAPHICAL REPRESENTATION OF THE PATTERN. CLASS DIAGRAMS AND INTERACTION DIAGRAMS CAN BE USED FOR THIS PURPOSE LIST OF CLASSES AND OBJECTS USED IN THE PATTERN AND THEIR ROLES IN THE DESIGN HOW CLASSES AND OBJECTS USED IN THE PATTERN INTERACT WITH EACH OTHER RESULTS, SIDE EFFECTS, AND TRADE OFFS CAUSED BY USING THE PATTERN IMPLEMENTATION OF THE PATTERN; THE SOLUTION PART OF THE PATTERN ILLUSTRATION OF HOW THE PATTERN CAN BE USED IN A PROGRAMMING LANGUAGE EXAMPLES OF REAL USAGES OF THE PATTERN OTHER PATTERNS THAT HAVE SOME RELATIONSHIP WITH THE PATTERN; DISCUSSION OF THE DIFFERENCES BETWEEN THE PATTERN AND SIMILAR PATTERNS
  • 56. 56SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS HOW TO SELECT A DESIGN PATTERN Study the intent section of the design pattern:
 what problem does it solve? Consider how the design patterns solves the problem Study related patterns of similar purpose Consider what should be variable in your design Introduce a pattern to refactor the design
  • 57. 57SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS HOW TO USE A DESIGN PATTERN Read pattern overview for its Applicability and Consequences Study the Structure, Participants and Collaboration sections Look at the Sample Code Choose names for the Participants (classes and methods)
 meaningful in your context Define the classes and appropriate interfaces Implement the operations to carry out the responsibilities and collaborations in the pattern
  • 58. 58SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS WHEN TO USE A DESIGN PATTERN Avoid overstructuring Only use design patterns when there is a real need. Introducing design patterns too early may be counterproductive.
 It makes the design structure unnecessarily complex. Do not waste the effort of introducing a design pattern
 if you are not sure that it will be needed.
  • 59. 59SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS WHEN TO USE A DESIGN PATTERN Avoid understructuring If there is a need for design patterns, use them! Use refactorings to introduce design patterns in existing code.
  • 61. 61SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS A SELECTION OF DESIGN PATTERNS ▸ Design pattern catalogue ▸ Factory Method ▸ Template Method ▸ Strategy ▸ Observer ▸ Decorator ▸ Visitor ▸ Singleton ▸ Composite ▸ Builder ▸ Iterator
  • 62. 62SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD FACTORY METHOD Classification: Class Creational. 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. Motivating example: Application framework for handling documents in a desktop application.
  • 63. 63SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD FACTORY METHOD : MOTIVATION Consider an application framework
 for creating desktop applications. Such applications work with documents. The framework contains basic operations
 for opening, closing and saving documents. Specific applications (e.g., subclasses of Application) can create their own kinds of documents (subclasses of Document) For example, a DrawingApplication creates DrawingDocuments. To create application-specific documents, the abstract Application class needs to delegate to its subclasses. Document open():void save(filename):void close():void Application docs:Document[] createDocument():Document
 newDocument(type):void openDocument(filename):void public void newDocument(String type) { Document doc = this.createDocument(type); docs.add(doc); doc.open(); }
  • 64. 64SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD FACTORY METHOD : MOTIVATION Document open():void save(filename):void close():void Application docs:Document[] createDocument():Document
 newDocument(type):void openDocument(filename):void public void newDocument(String type) { Document doc = this.createDocument(type); docs.add(doc); doc.open(); } DrawingApplication createDocument() public Document createDocument() { return new DrawingDocument() } DrawingDocument open():void save(filename):void close():void create
  • 65. 65SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD FACTORY METHOD : APPLICABILITY Use the Factory Method design pattern when: A class can’t anticipate the class of objects it must create A class wants its subclasses to specify the objects it creates Classes delegate responsibility to one of several helper subclasses, and you want to localise the knowledge of which helper classes to use
  • 66. 66SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD FACTORY METHOD : PARTICIPANTS Document open():void save(filename):void close():void Application docs:Document[] createDocument():Document
 newDocument(type):void openDocument(filename):void public void newDocument(String type) { Document doc = this.createDocument(type); docs.add(doc); doc.open(); } DrawingApplication createDocument() public Document createDocument() { return new DrawingDocument() } DrawingDocument open():void save(filename):void close():void PRODUCT CONCRETE
 PRODUCT CREATOR CONCRETE
 CREATORcreate
  • 67. 67SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD FACTORY METHOD : PARTICIPANTS Product (Document) Defines the interface of objects the factory method creates ConcreteProduct (DrawingDocument) Implements the Product interface Creator (Application) Declares the abstract factory method (createDocument) May call the factory method to create a Product object ConcreteCreator (DrawingApplication) Overrides factory method with a concrete one to return a ConcreteProduct instance
  • 68. 68SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD FACTORY METHOD : STRUCTURE Product 
 
 Creator factoryMethod() ConcreteCreator factoryMethod() ConcreteProduct create
  • 69. 69SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD FACTORY METHOD : COLLABORATIONS Creator relies on its ConcreteCreator subclasses
 to specify the concrete factory method so that it returns an instance of the appropriate ConcreteProduct
  • 70. 70SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD FACTORY METHOD: CONSEQUENCES More reusable than creating objects directly Connects parallel class hierarchies Product ConcreteProductA Creator factoryMethod() ConcreteCreatorA factoryMethod() Client ConcreteCreatorB factoryMethod() ConcreteProductB create create
  • 71. 71SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD FACTORY METHOD: IMPLEMENTATION Variation 1: Some factory methods can provide a default. In that case the factory method is not abstract. Application docs:Document[] createDocument():Document
 newDocument(type):void openDocument(filename):void public Document createDocument(String type){ if (type.isEqual("drawing")) return new DrawingDocument(); … }
  • 72. 72SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: FACTORY METHOD FACTORY METHOD: IMPLEMENTATION Variation 2: Factory methods can be parameterised to return multiple kinds of products. e.g. pass an extra parameter to createDocument to specify the kind of Document to create.
  • 74. 74SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: TEMPLATE METHOD A SELECTION OF DESIGN PATTERNS ▸ Design pattern catalogue ▸ Factory Method ▸ Template Method ▸ Strategy ▸ Observer ▸ Decorator ▸ Visitor ▸ Singleton ▸ Composite ▸ Builder ▸ Iterator WILL BE DISCUSSED LATER WHEN TALKING ABOUT APPLICATION FRAMEWORKS
  • 76. 76SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: STRATEGY A SELECTION OF DESIGN PATTERNS ▸ Design pattern catalogue ▸ Factory Method ▸ Template Method ▸ Strategy ▸ Observer ▸ Decorator ▸ Visitor ▸ Singleton ▸ Composite ▸ Builder ▸ Iterator
  • 77. 77SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: STRATEGY STRATEGY Classification: Object Behavioural. Intent: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Motivating example: Different sorting algorithms String search in a text processor
  • 78. 78SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: STRATEGY STRATEGY: MOTIVATION There are common situations when classes differ only in their behaviour. For such cases it is a good idea to isolate the algorithms in separate classes in order to have the ability to select different algorithms at runtime. SearchAlgorithm2 searchFor(String, Text) SearchAlgorithm1 searchFor(String, Text) TextProcessor text : Text search(String)
  • 79. 79SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: STRATEGY STRATEGY: MOTIVATION There are common situations when classes differ only in their behaviour. For such cases it is a good idea to isolate the algorithms in separate classes in order to have the ability to select different algorithms at runtime. searcher SearchAlgorithm searchFor(String, Text) SearchAlgorithm2 searchFor(String, Text) SearchAlgorithm1 searchFor(String, Text) TextProcessor text : Text search(String) 1 search(String s) { … searcher.searchFor(s,text) … }
  • 80. 80SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: STRATEGY STRATEGY: APPLICABILITY Use the Strategy design pattern when Many related classes that differ only in their behaviour You need different variants of an algorithm An algorithm uses data that clients should not know about A class defines many behaviours
  • 81. 81SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: STRATEGY STRATEGY: PARTICIPANTS Strategy (SearchAlgorithm) Declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy ConcreteStrategy (SearchAlgorithm1, SearchAlgorithm2) Implements the algorithm using the Strategy interface Context (TextProcessor) Is configured with a ConcreteStrategy object Maintains a reference to a Strategy object May define an interface that lets Strategy access its data
  • 82. 82SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: STRATEGY STRATEGY: STRUCTURE Strategy algorithmInterface() Strategy2 algorithmInterface() Strategy1 algorithmInterface() Context strategy : Strategy
 contextInterface() 1 strategy contextInterface() { … strategy.algorithmInterface() … }
  • 83. 83SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: STRATEGY STRATEGY: COLLABORATIONS Strategy and Context interact to implement the chosen algorithm Context may pass all data required by the algorithm to the strategy when the algorithm is called Context can pass itself as an argument to Strategy operations A Context forwards requests from its clients to its strategy Clients usually create and pass a ConcreteStrategy object to the Context. From then on, they interact with the Context exclusively.
  • 84. 84SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: STRATEGY STRATEGY: CONSEQUENCES Families of related algorithms An alternative to subclassing Strategies eliminate conditionals Provide a choice of implementation allow for different implementations of same behaviour Overhead involved Communication between Context and Strategy Increased number of objects
  • 85. 85SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: STRATEGY STRATEGY: IMPLEMENTATION The Strategy interface must provide enough information to ConcreteStrategy Default behaviour can be incorporated in the Context object. If no strategy object is present, this default behaviour can be used.
  • 87. 87SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: DECORATOR A SELECTION OF DESIGN PATTERNS ▸ Design pattern catalogue ▸ Factory Method ▸ Template Method ▸ Strategy ▸ Observer ▸ Decorator ▸ Visitor ▸ Singleton ▸ Composite ▸ Builder ▸ Iterator
  • 88. 88SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: DECORATOR DECORATOR Classification: Object Structural. Intent: Attach additional responsibilities to an object dynamically. Decorators provide a dynamic alternative for subclassing. Motivating example: Adding borders/scrollbars/… to a visual component
  • 89. 89SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: DECORATOR DECORATOR: MOTIVATION Traditional solution impractical when I want to apply different decorations to a same component when I want to apply a same decoration to different components VisualComponent draw() TextViewWithBorder draw() drawBorder() TextViewWithScrollBar draw() scrollTo() draw() { super.draw(); drawBorder() } TextView draw()
  • 90. 90SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: DECORATOR DECORATOR: MOTIVATION component VisualComponent draw() TextView draw() Decorator draw() BorderDecorator draw() drawBorder() ScrollDecorator draw() scrollTo() 1 draw() { … component.draw() … } draw() { super.draw(); drawBorder() } Solution with decorator
 design pattern
  • 91. 91SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: DECORATOR DECORATOR: APPLICABILITY Use the Decorator design pattern To add responsibilities to individual objects dynamically and transparently without affecting other objects For responsibilities that can be withdrawn When extending by subclassing is impractical
  • 92. 92SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: DECORATOR DECORATOR: PARTICIPANTS Component (VisualComponent) Defines the interface for objects that can have responsibilities added to them dynamically ConcreteComponent (TextView) Defines an object to which we want to attach additional responsibilities Decorator (Decorator) Maintains a reference to a Component object and defines an interface that conforms to the Components interface ConcreteDecorator (BorderDecorator) Adds responsibilities to the component
  • 93. 93SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: DECORATOR DECORATOR: MOTIVATION component Component operation() ConcreteComponent operation() Decorator operation() ConcreteDecoratorB added state operation() ConcreteDecoratorA added state operation() 1 operation() { … component.operation() … } operation() { super.operation(); …added behaviour… }
  • 94. 94SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: DECORATOR DECORATOR: COLLABORATIONS Decorator forwards requests to the Component object. It may optionally perform additional behaviour before and after forwarding the request
  • 95. 95SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: DECORATOR DECORATOR: CONSEQUENCES More flexible than static inheritance Possible to dynamically add or withdraw responsibilities Avoids classes with a lot of features Lots of little objects
  • 96. 96SOFTWARE PATTERNS – SELECTED DESIGN PATTERNS: DECORATOR DECORATOR: IMPLEMENTATION Object identity can be a problem a decorated component is not identical to the object itself
  • 98. F. ANTIPATTERNS LINGI2252 – PROF. KIM MENS * Slides party reused from slides by Prof. Tom Mens at UMons, Belgium *
  • 99. SOFTWARE PATTERNS – ANTI PATTERNS KEY REFERENCE Anti Patterns Refactoring Software, Architectures and Projects in Crisis W. J. Brown
 R. C. Malveau
 H. W. McCormick
 T.J. Mowbray
 John Wiley & Sons, 1997 99
  • 100. 100SOFTWARE PATTERNS – ANTI PATTERNS WHAT ARE ANTIPATTERNS? Design patterns identify good working practices Anti patterns identify common mistakes and how these mistakes can be overcome in refactored solutions. An AntiPattern is “a commonly used solution to a problem that generates decidedly negative consequences”
  • 101. 101SOFTWARE PATTERNS – ANTI PATTERNS WHAT ARE ANTIPATTERNS? An AntiPattern is a special (negative) design pattern
 which features an extra refactored solution to the problem. Context Forces Problem Solution Pattern Context Forces Problem Negative Solution AntiPattern Problem Refactored Solution
  • 102. 102SOFTWARE PATTERNS – ANTI PATTERNS 7 DEADLY SINS 1. Haste : Hasty decisions lead to compromises in software quality. Especially testing is a victim. “Just clean up the code, we ship tomorrow…” 2. Apathy : Not caring about solving known problems “Reuse? Who’s ever gonna reuse this crappy code?” 3. Narrow-mindedness : Refusal to practice solutions that are widely known to be effective. “I don’t need to know, and… I don’t care to know”
  • 103. 103SOFTWARE PATTERNS – ANTI PATTERNS 7 DEADLY SINS 4. Sloth (lazyness) : Making poor decisions based upon easy answers (lazy developers) 5. Avarice (greed) : The modeling of excessive details, resulting in overcomplexity due to insufficient abstraction “I’m impressed ! The most complex model ever done !” 6. Ignorance : Failing to seek understanding “100 pages… let’s find a one page summary on the net” 7. Pride : Reinventing designs instead of reusing them.
  • 104. 104SOFTWARE PATTERNS – ANTI PATTERNS CATEGORIES OF ANTIPATTERNS Development AntiPatterns technical problems/solutions encountered by programmers Architectural AntiPatterns identification of common problems in system structures Managerial AntiPatterns addresses common problems in software processes and development organisations
  • 105. 105SOFTWARE PATTERNS – ANTI PATTERNS DEVELOPMENT ANTIPATTERNS The Blob Continuous Obsolescence Lava Flow Ambiguous Viewpoint Functional Decomposition Poltergeists Golden Hammer Boat Anchor Dead End Spaghetti Code Minefield Walking Cut-and-Paste
  • 106. 106SOFTWARE PATTERNS – ANTI PATTERNS EXAMPLE: THE BLOB Category : Software Development Also Known As : The God Class Scale : Application Refactored Solution Name : Refactoring of Responsibilities Root Causes : Sloth, Haste
  • 107. 107SOFTWARE PATTERNS – ANTI PATTERNS THE BLOB: GENERAL FORM Designs where one class monopolises the processing, and other classes primarily encapsulate data Key problem: majority of responsibilities allocated to a single class. In general it is a kind of procedural design conflicts with OO paradigm
  • 108. 108SOFTWARE PATTERNS – ANTI PATTERNS THE BLOB: REFACTORED SOLUTION Identify or categorise related attributes and operations Look for ‘natural homes’ for these collections of functionality Apply OO design techniques (e.g., inheritance, …) Apply refactorings to bring code back in shape
  • 109. G. CONCLUSION LINGI2252 – PROF. KIM MENS
  • 110. 110SOFTWARE PATTERNS – CONCLUSION SOFTWARE PATTERNS … capture successful solutions to recurring problems that arise during software construction define a common vocabulary amongst software developers increase reuse of design as opposed to reuse of implementation help to improve software quality can be introduced by refactoring should be used with care! (anti patterns)
  • 111. 111SOFTWARE PATTERNS – CONCLUSION ARCHITECTURAL AND DESIGN PATTERNS ARE Smart provide elegant solutions that a novice would not think of Generic independent of a specific system or programming language Well-proven successfully tested and applied in several real-world applications
  • 113. 113SOFTWARE PATTERNS – QUESTIONS POSSIBLE QUESTIONS (1) ▸ What do Christopher Alexander’s (building) architectural patterns and (software) design patterns have in common? Explain with a concrete example. ▸ Give a definition of the notion of “design pattern”. ▸ What are design patterns good for and why? Why cannot you say “I have invented a design pattern”? ▸ Explain the different parts of which a design pattern description typically exists. ▸ (Catchy name, Classification, Intent, Also known as, Motivation, Applicability, Structure, Participants, Collaboration, Consequences, Implementation, Sample Code, Known Uses, Related Patterns)
  • 114. 114SOFTWARE PATTERNS – QUESTIONS POSSIBLE QUESTIONS (2) ▸ Explain and illustrate the Abstract Factory design pattern in detail. Clearly mention its problem, solution, participants, structure and applicability. ▸ Explain the Factory Method design pattern in detail. Clearly mention its Intent, Motivation, Applicability, Participants, Collaboration, Consequences and Implementation. ▸ Same question for the Strategy and Decorator design patterns. ▸ What is an antipattern and how does it compare to a design pattern? What purpose does it serve? ▸ Explain at least 4 of the 7 deadly sins related to antipatterns. ▸ Explain The Blob antipattern.