SlideShare une entreprise Scribd logo
1  sur  114
Télécharger pour lire hors ligne
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
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.

Contenu connexe

Tendances

Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan GoleChetan Gole
 
Introduction to design patterns
Introduction to design patternsIntroduction to design patterns
Introduction to design patternsAmit Kabra
 
Ch3-Software Engineering 9
Ch3-Software Engineering 9Ch3-Software Engineering 9
Ch3-Software Engineering 9Ian Sommerville
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design patternMindfire Solutions
 
Introduction to SOFTWARE ARCHITECTURE
Introduction to SOFTWARE ARCHITECTUREIntroduction to SOFTWARE ARCHITECTURE
Introduction to SOFTWARE ARCHITECTUREIvano Malavolta
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General IntroductionAsma CHERIF
 
UML and Software Modeling Tools.pptx
UML and Software Modeling Tools.pptxUML and Software Modeling Tools.pptx
UML and Software Modeling Tools.pptxNwabueze Obioma
 
Introduction to WEB engineering TERMINOLOGIES
Introduction to WEB engineering TERMINOLOGIESIntroduction to WEB engineering TERMINOLOGIES
Introduction to WEB engineering TERMINOLOGIESSofthat IT Solutions
 
Software product line
Software product lineSoftware product line
Software product lineHimanshu
 
SE2018_Lec 18_ Design Principles and Design Patterns
SE2018_Lec 18_ Design Principles and Design PatternsSE2018_Lec 18_ Design Principles and Design Patterns
SE2018_Lec 18_ Design Principles and Design PatternsAmr E. Mohamed
 
Software Re-engineering Forward & Reverse Engineering
Software Re-engineering Forward & Reverse EngineeringSoftware Re-engineering Forward & Reverse Engineering
Software Re-engineering Forward & Reverse EngineeringAli Raza
 
Ch5- Software Engineering 9
Ch5- Software Engineering 9Ch5- Software Engineering 9
Ch5- Software Engineering 9Ian Sommerville
 
Software architecture
Software architectureSoftware architecture
Software architecturenazn
 

Tendances (20)

Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan Gole
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
Introduction to design patterns
Introduction to design patternsIntroduction to design patterns
Introduction to design patterns
 
Ch5 system modeling
Ch5 system modelingCh5 system modeling
Ch5 system modeling
 
Design patterns tutorials
Design patterns tutorialsDesign patterns tutorials
Design patterns tutorials
 
Ch3-Software Engineering 9
Ch3-Software Engineering 9Ch3-Software Engineering 9
Ch3-Software Engineering 9
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
 
Introduction to SOFTWARE ARCHITECTURE
Introduction to SOFTWARE ARCHITECTUREIntroduction to SOFTWARE ARCHITECTURE
Introduction to SOFTWARE ARCHITECTURE
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General Introduction
 
Design Patterns.ppt
Design Patterns.pptDesign Patterns.ppt
Design Patterns.ppt
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
UML and Software Modeling Tools.pptx
UML and Software Modeling Tools.pptxUML and Software Modeling Tools.pptx
UML and Software Modeling Tools.pptx
 
Introduction to WEB engineering TERMINOLOGIES
Introduction to WEB engineering TERMINOLOGIESIntroduction to WEB engineering TERMINOLOGIES
Introduction to WEB engineering TERMINOLOGIES
 
DESIGN PATTERNS: Strategy Patterns
DESIGN PATTERNS: Strategy PatternsDESIGN PATTERNS: Strategy Patterns
DESIGN PATTERNS: Strategy Patterns
 
Software product line
Software product lineSoftware product line
Software product line
 
SE2018_Lec 18_ Design Principles and Design Patterns
SE2018_Lec 18_ Design Principles and Design PatternsSE2018_Lec 18_ Design Principles and Design Patterns
SE2018_Lec 18_ Design Principles and Design Patterns
 
Ch15 software reuse
Ch15 software reuseCh15 software reuse
Ch15 software reuse
 
Software Re-engineering Forward & Reverse Engineering
Software Re-engineering Forward & Reverse EngineeringSoftware Re-engineering Forward & Reverse Engineering
Software Re-engineering Forward & Reverse Engineering
 
Ch5- Software Engineering 9
Ch5- Software Engineering 9Ch5- Software Engineering 9
Ch5- Software Engineering 9
 
Software architecture
Software architectureSoftware architecture
Software architecture
 

Similaire à Software Patterns

Contemporary Software Engineering Practices Together With Enterprise
Contemporary Software Engineering Practices Together With EnterpriseContemporary Software Engineering Practices Together With Enterprise
Contemporary Software Engineering Practices Together With EnterpriseKenan Sevindik
 
Cs 1023 lec 9 design pattern (week 2)
Cs 1023 lec 9 design pattern (week 2)Cs 1023 lec 9 design pattern (week 2)
Cs 1023 lec 9 design pattern (week 2)stanbridge
 
OOSE Unit 4 PPT.ppt
OOSE Unit 4 PPT.pptOOSE Unit 4 PPT.ppt
OOSE Unit 4 PPT.pptitadmin33
 
5 Design Patterns Explained
5 Design Patterns Explained5 Design Patterns Explained
5 Design Patterns ExplainedPrabhjit Singh
 
Oose unit 4 ppt
Oose unit 4 pptOose unit 4 ppt
Oose unit 4 pptDr VISU P
 
SADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdfSADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdfB.T.L.I.T
 
Java Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaJava Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaEdureka!
 
Software Engineering- Crisis and Process Models
Software Engineering- Crisis and Process ModelsSoftware Engineering- Crisis and Process Models
Software Engineering- Crisis and Process ModelsNishu Rastogi
 
04 designing architectures
04 designing architectures04 designing architectures
04 designing architecturesMajong DevJfu
 
02 architectures in_context
02 architectures in_context02 architectures in_context
02 architectures in_contextMajong DevJfu
 
Module 2 design patterns-2
Module 2   design patterns-2Module 2   design patterns-2
Module 2 design patterns-2Ankit Dubey
 
[2015/2016] Software systems engineering PRINCIPLES
[2015/2016] Software systems engineering PRINCIPLES[2015/2016] Software systems engineering PRINCIPLES
[2015/2016] Software systems engineering PRINCIPLESIvano Malavolta
 
Software Architecture for Agile Development
Software Architecture for Agile DevelopmentSoftware Architecture for Agile Development
Software Architecture for Agile DevelopmentHayim Makabee
 
MWLUG 2015 - An Introduction to MVC
MWLUG 2015 - An Introduction to MVCMWLUG 2015 - An Introduction to MVC
MWLUG 2015 - An Introduction to MVCUlrich Krause
 
An Introduction To Model  View  Controller In XPages
An Introduction To Model  View  Controller In XPagesAn Introduction To Model  View  Controller In XPages
An Introduction To Model  View  Controller In XPagesUlrich Krause
 

Similaire à Software Patterns (20)

Contemporary Software Engineering Practices Together With Enterprise
Contemporary Software Engineering Practices Together With EnterpriseContemporary Software Engineering Practices Together With Enterprise
Contemporary Software Engineering Practices Together With Enterprise
 
Cs 1023 lec 9 design pattern (week 2)
Cs 1023 lec 9 design pattern (week 2)Cs 1023 lec 9 design pattern (week 2)
Cs 1023 lec 9 design pattern (week 2)
 
OOSE Unit 4 PPT.ppt
OOSE Unit 4 PPT.pptOOSE Unit 4 PPT.ppt
OOSE Unit 4 PPT.ppt
 
5 Design Patterns Explained
5 Design Patterns Explained5 Design Patterns Explained
5 Design Patterns Explained
 
Oose unit 4 ppt
Oose unit 4 pptOose unit 4 ppt
Oose unit 4 ppt
 
SADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdfSADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdf
 
Java Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaJava Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | Edureka
 
xCP Pattern Library 3.3
xCP Pattern Library 3.3xCP Pattern Library 3.3
xCP Pattern Library 3.3
 
Software Engineering- Crisis and Process Models
Software Engineering- Crisis and Process ModelsSoftware Engineering- Crisis and Process Models
Software Engineering- Crisis and Process Models
 
04 designing architectures
04 designing architectures04 designing architectures
04 designing architectures
 
010821+presentation+oti.ppt
010821+presentation+oti.ppt010821+presentation+oti.ppt
010821+presentation+oti.ppt
 
02 architectures in_context
02 architectures in_context02 architectures in_context
02 architectures in_context
 
Module 2 design patterns-2
Module 2   design patterns-2Module 2   design patterns-2
Module 2 design patterns-2
 
CHAPTER12.ppt
CHAPTER12.pptCHAPTER12.ppt
CHAPTER12.ppt
 
.Net design pattern
.Net design pattern.Net design pattern
.Net design pattern
 
[2015/2016] Software systems engineering PRINCIPLES
[2015/2016] Software systems engineering PRINCIPLES[2015/2016] Software systems engineering PRINCIPLES
[2015/2016] Software systems engineering PRINCIPLES
 
SA_UNIT_1.pptx
SA_UNIT_1.pptxSA_UNIT_1.pptx
SA_UNIT_1.pptx
 
Software Architecture for Agile Development
Software Architecture for Agile DevelopmentSoftware Architecture for Agile Development
Software Architecture for Agile Development
 
MWLUG 2015 - An Introduction to MVC
MWLUG 2015 - An Introduction to MVCMWLUG 2015 - An Introduction to MVC
MWLUG 2015 - An Introduction to MVC
 
An Introduction To Model  View  Controller In XPages
An Introduction To Model  View  Controller In XPagesAn Introduction To Model  View  Controller In XPages
An Introduction To Model  View  Controller In XPages
 

Plus de kim.mens

Software Maintenance and Evolution
Software Maintenance and EvolutionSoftware Maintenance and Evolution
Software Maintenance and Evolutionkim.mens
 
Context-Oriented Programming
Context-Oriented ProgrammingContext-Oriented Programming
Context-Oriented Programmingkim.mens
 
Software Reuse and Object-Oriented Programming
Software Reuse and Object-Oriented ProgrammingSoftware Reuse and Object-Oriented Programming
Software Reuse and Object-Oriented Programmingkim.mens
 
Bad Code Smells
Bad Code SmellsBad Code Smells
Bad Code Smellskim.mens
 
Object-Oriented Design Heuristics
Object-Oriented Design HeuristicsObject-Oriented Design Heuristics
Object-Oriented Design Heuristicskim.mens
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoringkim.mens
 
Domain Modelling
Domain ModellingDomain Modelling
Domain Modellingkim.mens
 
Object-Oriented Application Frameworks
Object-Oriented Application FrameworksObject-Oriented Application Frameworks
Object-Oriented Application Frameworkskim.mens
 
Towards a Context-Oriented Software Implementation Framework
Towards a Context-Oriented Software Implementation FrameworkTowards a Context-Oriented Software Implementation Framework
Towards a Context-Oriented Software Implementation Frameworkkim.mens
 
Towards a Taxonomy of Context-Aware Software Variabilty Approaches
Towards a Taxonomy of Context-Aware Software Variabilty ApproachesTowards a Taxonomy of Context-Aware Software Variabilty Approaches
Towards a Taxonomy of Context-Aware Software Variabilty Approacheskim.mens
 
Breaking the Walls: A Unified Vision on Context-Oriented Software Engineering
Breaking the Walls: A Unified Vision on Context-Oriented Software EngineeringBreaking the Walls: A Unified Vision on Context-Oriented Software Engineering
Breaking the Walls: A Unified Vision on Context-Oriented Software Engineeringkim.mens
 
Context-oriented programming
Context-oriented programmingContext-oriented programming
Context-oriented programmingkim.mens
 
Basics of reflection
Basics of reflectionBasics of reflection
Basics of reflectionkim.mens
 
Advanced Reflection in Java
Advanced Reflection in JavaAdvanced Reflection in Java
Advanced Reflection in Javakim.mens
 
Basics of reflection in java
Basics of reflection in javaBasics of reflection in java
Basics of reflection in javakim.mens
 
Reflection in Ruby
Reflection in RubyReflection in Ruby
Reflection in Rubykim.mens
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to Rubykim.mens
 
Introduction to Smalltalk
Introduction to SmalltalkIntroduction to Smalltalk
Introduction to Smalltalkkim.mens
 
A gentle introduction to reflection
A gentle introduction to reflectionA gentle introduction to reflection
A gentle introduction to reflectionkim.mens
 
Managing the Evolution of Information Systems with Intensional Views and Rela...
Managing the Evolution of Information Systems with Intensional Views and Rela...Managing the Evolution of Information Systems with Intensional Views and Rela...
Managing the Evolution of Information Systems with Intensional Views and Rela...kim.mens
 

Plus de kim.mens (20)

Software Maintenance and Evolution
Software Maintenance and EvolutionSoftware Maintenance and Evolution
Software Maintenance and Evolution
 
Context-Oriented Programming
Context-Oriented ProgrammingContext-Oriented Programming
Context-Oriented Programming
 
Software Reuse and Object-Oriented Programming
Software Reuse and Object-Oriented ProgrammingSoftware Reuse and Object-Oriented Programming
Software Reuse and Object-Oriented Programming
 
Bad Code Smells
Bad Code SmellsBad Code Smells
Bad Code Smells
 
Object-Oriented Design Heuristics
Object-Oriented Design HeuristicsObject-Oriented Design Heuristics
Object-Oriented Design Heuristics
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoring
 
Domain Modelling
Domain ModellingDomain Modelling
Domain Modelling
 
Object-Oriented Application Frameworks
Object-Oriented Application FrameworksObject-Oriented Application Frameworks
Object-Oriented Application Frameworks
 
Towards a Context-Oriented Software Implementation Framework
Towards a Context-Oriented Software Implementation FrameworkTowards a Context-Oriented Software Implementation Framework
Towards a Context-Oriented Software Implementation Framework
 
Towards a Taxonomy of Context-Aware Software Variabilty Approaches
Towards a Taxonomy of Context-Aware Software Variabilty ApproachesTowards a Taxonomy of Context-Aware Software Variabilty Approaches
Towards a Taxonomy of Context-Aware Software Variabilty Approaches
 
Breaking the Walls: A Unified Vision on Context-Oriented Software Engineering
Breaking the Walls: A Unified Vision on Context-Oriented Software EngineeringBreaking the Walls: A Unified Vision on Context-Oriented Software Engineering
Breaking the Walls: A Unified Vision on Context-Oriented Software Engineering
 
Context-oriented programming
Context-oriented programmingContext-oriented programming
Context-oriented programming
 
Basics of reflection
Basics of reflectionBasics of reflection
Basics of reflection
 
Advanced Reflection in Java
Advanced Reflection in JavaAdvanced Reflection in Java
Advanced Reflection in Java
 
Basics of reflection in java
Basics of reflection in javaBasics of reflection in java
Basics of reflection in java
 
Reflection in Ruby
Reflection in RubyReflection in Ruby
Reflection in Ruby
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to Ruby
 
Introduction to Smalltalk
Introduction to SmalltalkIntroduction to Smalltalk
Introduction to Smalltalk
 
A gentle introduction to reflection
A gentle introduction to reflectionA gentle introduction to reflection
A gentle introduction to reflection
 
Managing the Evolution of Information Systems with Intensional Views and Rela...
Managing the Evolution of Information Systems with Intensional Views and Rela...Managing the Evolution of Information Systems with Intensional Views and Rela...
Managing the Evolution of Information Systems with Intensional Views and Rela...
 

Dernier

Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 

Dernier (20)

Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 

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
  • 112.
  • 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.