Corso di Ingegneria del Software
Paolo Bottoni
Lezione 11: Pattern di progetto
Lezione11Design PatternIngegneria del Software 2
Obiettivi
• Introdurre il concetto di Pattern di Progetto
• Illustrare alcuni pattern significativi
• Mostrarne la specifica originale
• Introdurre una notazione per variabilità
Design pattern
• Introdotti (23 pattern) in:Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Design
Patterns: Elements of Reusable Object-Oriented Software, Wiley, 1995
• Soluzioni generiche a problemi ricorrenti
• Definiscono ruoli e comportamenti di classi
• Associati con:
– Descrizioni
– Esempi
– Motivazioni
– Varianti,
– Conseguenze
Lezione11Design PatternIngegneria del Software 3
Principi
• Program to an 'interface', not an 'implementation'
• Favor 'object composition' over 'class inheritance'
• Astrazione da caratteristiche oggetti
Lezione11Design PatternIngegneria del Software 4
Catalogazione
• Creational
– Singleton, AbstractFactory, FactoryMethod, Builder,
Prototype
• Structural
– Adapter, Bridge, Composite, Decorator, Façade, Proxy
• Behavioural
– Chain of responsibility, Command, Interpreter, Iterator,
Mediator, Memento, Observer, State, Strategy,
Template method, Visitor
Lezione11Design PatternIngegneria del Software 5
Pattern di creazione
• Astrazione processo instanziazione
• Rendono sistema indipendente da creazione,
composizione, rappresentazione oggetti
• Orientati a classi
– Usano ereditarietà per variazione classe
• Orientati a oggetti
– Istanziazione delegata ad altro oggetto
Lezione11Design PatternIngegneria del Software 6
Abstract factory
• Esempio: supporto LaF multipli
Lezione11Design PatternIngegneria del Software 7
Descrizione strutturale
Lezione11Design PatternIngegneria del Software 8
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 9
+ createX()
<<Abstract Factory>>
AbstractFactory
<<Concrete Factory>>
Y+”Factory”
factories
<<Abstract Product>>
X
absProducts
+ “create”+X ()
<<Concrete Product>>
X+Y
concProducts
AbstractFactory>=0, factories>0, absProducts>0, factories=concProducts
AbstractFactory
<<creationOp>>
<<Client>>
Client
Specifica formale: comportamento
Lezione11Design PatternIngegneria del Software 10
:Y+”Factory”
<<creationOp>>”create”+X ()
<<create>>
absProductsconcProducts
:X+Y
class
<<Concrete Product>>
X+Y
factories<<Concrete Factory>>
Y+”Factory”
class
AbstractFactory
:Client
<<Client>>
Client
class
Builder
• Esempio: conversione da RTF ad altri formati
Lezione11Design PatternIngegneria del Software 11
Descrizione strutturale
Lezione11Design PatternIngegneria del Software 12
Descrizione comportamentale
Lezione11Design PatternIngegneria del Software 13
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 14
+ Director (Builder) <<constructor>>
+ Construct () <<builderOP>>
<<Director>>
Director<<Builder>>
BuilderBUILDER
<<ConcreteBuilder>>
ConcreteBuilder
+GetResult () <<getResults>>
<<Product>>
Product
concreteBuilders
Builder
Builder>=0, concreteBuilders>0, parts>0
+ BuildPart () <<buildParts>>
parts
<<builderRole>>
For all objects in structure {
BUILDER.BuildPart ()
}
Specifica formale: comportamento
Lezione11Design PatternIngegneria del Software 15
aClient :
<<create>>CB : ConcreteBuilder
: Director<<create>>
new Director (CB)
<<builderOP>>
Construct () <<buildParts>>
BuildPart ()
concreteBuilders
parts
<<Director>>
Director<<ConcreteBuilder>>
ConcreteBuilder
classclass
Builder
Factory method
• Esempio: framework per definire
applicazioni che creano documenti
– Classi principali sono astratte
Lezione11Design PatternIngegneria del Software 16
Specifica formale: struttur
Usabile anche per dipendenze fra gerarchie
Lezione11Design PatternIngegneria del Software 17
Descrizione strutturale
Lezione11Design PatternIngegneria del Software 18
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 19
<<Creator>>
Creator
+OP() <<opUsrFactMethod>>
+FactoryMethod () <<factoryMethod>><<Product>>
Product
<<ConcreteProduct>>
ConcreteProduct<<ConcreteCreator>>
ConcreteCreator
+FactoryMethod ( ) <<concFactoryMethod>>
creatorsreturn new ConcreteProduct ()
FactoryMethod
FactoryMethod>=0, ops>0, creators>0
ops
Specifica formale: comportamento
Lezione11Design PatternIngegneria del Software 20
CC : ConcreteCreator
OP ()
FactoryMethod () <<concFactoryMethod>>
CP: ConcreteProduct<<create>>
return CP
creators
FactoryMethod
<<ConcreteProduct>>
ConcreteProduct<<ConcreteCreator>>
ConcreteCreator
class class
<<opUsrFactMethod>>
ops
Prototype
• Esempio: ambiente grafico da specializzare
a creazione musicale
Lezione11Design PatternIngegneria del Software 21
Descrizione strutturale
Lezione11Design PatternIngegneria del Software 22
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 23
+ Clone () <<cloneOp>>
<<Prototype>>
Prototype
+ Clone () <<concCloneOp>>
<<ConcretePrototype>>
ConcretePrototype
prototypes
Prototype
Prototype>=0, prototypes>0
<<Client>>
Client
+ Operation () <<clientOp>>
prototype
<<prototypeRel>>
prototype.Clone()
Singleton
• Motivazione: garantire unicità istanza di
classe in applicazione
Lezione11Design PatternIngegneria del Software 24
Descrizione strutturale
Lezione11Design PatternIngegneria del Software 25
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 26
- Instance : Singleton <<instance>>
- Singleton (…) <<constructor>>
+ GetInstance(…) : Singleton <<getter>>
+ Singleton (…)
# Singleton (…)
<<Singleton>>
Singleton
X
X
Singleton
Singleton>=0
Specifica formale: comportamento
Lezione11Design PatternIngegneria del Software 27
<<Singleton>>
Singleton
GetInstance (…)
<<getter>><<instance>>
Instance: Singleton<<create>>
[Instance==null]opt
return Instance
class
Singleton
Pattern strutturali
• Riguardano composizione di classi e oggetti in
strutture più ampie
• Composizione a livello di classe, basata su
ereditarietà
• Composizione a livello di istanza, basata su
composizione per ottenere nuove funzionalità
Lezione11Design PatternIngegneria del Software 28
Adapter
• Esempio: riuso di classe per gestire testo
Lezione11Design PatternIngegneria del Software 29
Descrizione struttura (classe o oggetto)
Lezione11Design PatternIngegneria del Software 30
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 31
<<Target>>
Target<<Adaptee>>
Adaptee<<Adapter>>
Adapter
+ X () <<request>> + X () <<AdapterRequest>> + Y () <<SpecificRequest>>
<<Target>>
Target<<Adaptee>>
Adaptee
<<Adapter>>
Adapter
+ X () <<request>> + X () <<AdapterRequest>> + Y () <<SpecificRequest>>
ad
ClassAdapter
requests
requests
ObjectAdapter
ClassAdapter >=0, requests>0
ObjectAdapter >=0, requests>0
<<adRole>>
<<Client>>
Client
<<Client>>
Client
Specifica formale: comportamento
Lezione11Design PatternIngegneria del Software 32
:Adapter
<<request>>X ()
ad:Adaptee
<<SpecificRequest>>Y ()
requests
:Adapter
<<request>>
X ()
<<SpecificRequest>>Y ()
requests
:Client
<<Client>>
Client
class
<<Target>>
:Adapter
class
:Client
<<Client>>
Client<<Target>>
Adapter<<Adaptee>>
Adaptee
class classclass
ClassAdapter ObjectAdapter
Bridge • Esempio: sviluppo multipiattaforma
Lezione11Design PatternIngegneria del Software 33
X
Descrizione strutturale
Lezione11Design PatternIngegneria del Software 34
Composite
• Esempio: gestione grafica astraendo da
natura oggetti presenti
Lezione11Design PatternIngegneria del Software 35
Descrizione struttura
Lezione11Design PatternIngegneria del Software 36
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 37
* CHILDREN<<children>>
<<Component>>
Component
<<Leaf>>
Leaf
Composite
+ Add (Component) <<add>>
+ Remove (Component) <<remove>>
+ GetChild (int) : Component <<getChild>>
+ OP (…) <<absOperation>>
leafs
X
+OP (…)
for all c in CHILDREN:
c.OP (…)
<<Composite>>
Composite
operations
Composite>=0, operations>0, leafs>0
<<compOperation>>
<<Client>>
Client
Specifica formale: comportamento
Lezione11Design PatternIngegneria del Software 38
C in CHILDRENloop
: Composite
<<compOperation>>
OP (…)
C: Component
OP (…)
operations
<<Composite>>
Composite<<Component>>
Component
class class
Composite
Specifica formale
Lezione11Design PatternIngegneria del Software 39
<<Abstraction>>
Abstraction
<<Refined Abstraction>>
RefinedAbs
refinements
<<Implementor>>
Implementor
<<Concrete Implementor>>
CY
implementors
Bridge>=0, operations>0, implementors>0, refinements>0, extInterface>0
Bridge
IMP
+ OP () + OPI () <<operImpl>>
<<oper>>operations
+ ROP () <<refOper>>
extInterface
<<impRole>>
Specifica formale: comportamento
Lezione11Design PatternIngegneria del Software 40
Bridge
: RefinedAbs
<<oper>>
OP ()
: Implementor
OPI ()<<operImpl>>
operations
<<Refined Abstraction>>
RefinedAbs<<Implementor>>
Implementor
class class
Decorator
• Motivazione: aggiunta flessibile di
comportamenti a oggetti
Lezione11Design PatternIngegneria del Software 41
Esempio e descrizione strutturale
Lezione11Design PatternIngegneria del Software 42
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 43
+ OP (…) <<operation>>
<<Component>>
Component
<<Decorator>>
Decorator
<<ConcreteDecorator>>
ConcDecorator
<<ConcreteComponent>>
ConcComponent
COMPONENT
concComps
concDecos
Decorator
Decorator>=0, concComps>0, concDecos>0
0..1 <<compRole>>
XX<<Strategy::Context>>
Specifica formale: comportamento
Lezione11Design PatternIngegneria del Software 44
D: Decorator<<operation>>
1: OP (…)C: Component
COMPONENT<<operation>>
1.1: OP (…)
<<compRole>>
<<Decorator>>
Decorator<<Component>>
Component
class class
Decorator
Facade
• Esempio: compilatore nasconde fasi diverse
Lezione11Design PatternIngegneria del Software 45
Descrizione strutturale
Lezione11Design PatternIngegneria del Software 46
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 47
<<Facade>>
Facade
<<Subsystem Class>>
SUBClass
{isAbstract=ANY}
subsystems
+ OP () <<operation>>
facInterface
Facade
Facade>=0, facInterface>0, subsystems>0
<<Client>>
Client
XX
Flyweight
• Esempio: riuso di istanze in molte situazioni
in un editor
Lezione11Design PatternIngegneria del Software 48
Esempio
e
struttura
Lezione11Design PatternIngegneria del Software 49
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 50
<<FlyweightFactory>>
FlyweightFactory
+GetFlyWeight (key) <<getFW>>
<<Flyweight>>
Flyweight
+Operation (exState) <<oper>>
FLYWTS
<<ConcreteFlyweight>>
ConcFlyweight<<UnsharedConcreteFlyweight>>
UnsharedConcFlyweight
concFlyweights unsharedFlyweights
If (FLYWTS[key] exists) {
return existing flyweight
}
else {
create new flyweight;
add it to FLYWTS;
return the new flyweight;
}
Flyweight
Flyweight>=0, concFlyweights>0, unsharedFlyweights>=0
<<fwRole>>
X <<intrinsicState>> Y <<allState>>
Specifica formale: comportamento
Lezione11Design PatternIngegneria del Software 51
CF: ConcFlyweight
aClient : X
<<create>>
concFlyweightsX
UF: UnsharedConcFlyweight
unsharedFlyweights
aClient : X
<<create>>
X
<<ConcreteFlyweight>>
ConcFlyweight
<<UnsharedConcreteFlyweight>>
UnsharedConcFlyweight
class
class
Flyweight
Proxy
• Esempio e motivazioni: editor presenta immagine
solo quando necessario. In generale istanza
"esterna" a applicazione che la usa
Lezione11Design PatternIngegneria del Software 52
Descrizione strutturale
Lezione11Design PatternIngegneria del Software 53
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 54
+ Request () <<absReqOp>>
<<Subject>>
Subject
+ Request () <<proxyReq>>
<<Proxy>>
Proxy
+ Request () <<realReq>>
<<RealSubject>>
RealSubject
requests
Proxy
Proxy>=0, requests>0
RSubject<<rsRole>>
Specifica formale: comportamento
Lezione11Design PatternIngegneria del Software 55
P: Proxy
Request ()
<<proxyReq>>
RS: RealSubject
Request ()
<<realReq>>
requests
Proxy <<Proxy>>
Proxy<<RealSubject>>
RealSubject
class class
Behavioral patterns
• Specializzazione algoritmi e assegnazione
responsabiltà tra oggetti
• Specificano anche forme di comunicazione e flussi di
controllo complessi
• Versione classi distribuisce comportamento fra classi
• Versione oggetti descrive cooperazione fra gruppi
Lezione11Design PatternIngegneria del Software 56
Chain of Responsibility
• Esempio: livelli di help contestuali diversi o
risposta a eventi. Risponde il primo, in struttura
ordinata, in grado di farlo
Lezione11Design PatternIngegneria del Software 57
Descrizione strutturale
Lezione11Design PatternIngegneria del Software 58
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 59
+ HandleRequest () <<absRequest>>
<<Handler>>
Handler
successor
+ HandleRequest () <<concRequest>>
<<Concrete Handler>>
ConcreteHandler
concreteHandlers
ChainOfResponsibility
ChainOfResponsibility>=0, concreteHandlers>0
0..1<<succRole>>
<<Client>>
Client
Specifica formale comportamento
Lezione11Design PatternIngegneria del Software 60
h1 : Handler h2 : Handlersuccessor<<absRequest>>
1: HandleRequest () 1.1: HandleRequest ()
<<absRequest>>
<<Handler>>
Handler
class
class
:Client
<<Client>>
Client
class
ChainOfResponsibility
Command
• Motivazione ed esempio: in framework,
permettere attivazione di comportamenti,
senza conoscerne l'interfaccia
• Comportamento reificato in oggetto
Lezione11Design PatternIngegneria del Software 61
Contesto di esecuzione comando
Lezione11Design PatternIngegneria del Software 62
Descrizione strutturale
Lezione11Design PatternIngegneria del Software 63
Descrizione comportamento
Lezione11Design PatternIngegneria del Software 64
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 65
+ Execute () <<absExecuteOp>>
<<Command>>
Command<<Invoker>>
Invoker
<<Receiver>>
Receiver
+ Action () <<action>> + Execute () <<executeOp>>
+ ConcreteCommand (Receiver r)<<constructor>>
<<ConcreteCommand>>
ConcreteCommandREC
concreteCommands
Command
Command>=0, concreteCommands>0
+ Store (Command c) <<storeCommand>>
<<recRole>>
<<Client>>
Client
Specifica formale: comportamento
Lezione11Design PatternIngegneria del Software 66
: Client
CC : ConcreteCommand
RO: Receiver
new ConcreteCommand (RO)<<constructor>>
IN: Invoker
Store (CC)<<storeCommand>>
Execute ()<<executeOp>>Action ()
<<action>>
concreteCommands
<<Client>>
Client
class
<<Receiver>>
Receiver<<Invoker>>
Invoker<<ConcreteCommand>>
ConcreteCommand
class classclass
Command
Interpreter
• Rimpiazzare algoritmi specifici per ogni caso con
definizione di struttura di linguaggio dei casi.
Lezione11Design PatternIngegneria del Software 67
Descrizione strutturale
Lezione11Design PatternIngegneria del Software 68
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 69
<<AbstractExpression>>
AbstractExpression
+Interpret (ctxt) <<intOp>>
<<TerminalExpression>>
TerminalExpression<<NonTerminalExpression>>
NonTerminalExpressions
terminals nonTerminals
+Interpret (ctxt) <<concIntOp>> +Interpret (ctxt) <<concIntOp>>
X
Interpreter
Interpreter>=0, terminals>0, nonTerminals>0
<<Client>>
Client
<<Context>>
Context
Iterator
• Motivazione: esplorare una struttura secondo un
ordine, senza conoscerne l'implementazione
• Capacità di esplorazione dettata da oggetto esplorato
Lezione11Design PatternIngegneria del Software 70
Descrizione strutturale
Lezione11Design PatternIngegneria del Software 71
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 72
<<Iterator>>
Iterator
+First <<first>>
+Next () <<next>>
+IsDone () <<isDone>>
+CurrentItem () <<current>>
<<Aggregate>>
Aggregate
+createIterator () <<absCreate>>
<<ConcreteAggregate>>
ConcreteAggregate
+CreateIterator () <<concCreate>>
<<ConcreteIterator>>
ConcreteIterator
return new ConcreteIterator (this)
concreteAggregates
Iterator
Iterator>=0, concreteAggregates>0, concreteIterators>0
+ CreateIterator () <<concCreate>>
concreteIterators
Mediator • Motivazione: gestione
centralizzata di dipendenze
fra diversi oggetti
• Esempio: finestra di dialogo
complessa
Lezione11Design PatternIngegneria del Software 73
Descrizione strutturale
Lezione11Design PatternIngegneria del Software 74
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 75
<<Colleague>>
Colleague
<<ConcreteColleague>>
ConcColleague
<<Mediator>>
MediatorMED
<<ConcreteMediator>>
ConcMediator
concColleagues
Mediator
Mediator>=0, concColleagues>0
<<medRole>>
Memento
• Memorizza stato interno di un oggetto a un
determinato istante e permette di recuperarlo
Esempio: gestione undo
Lezione11Design PatternIngegneria del Software 76
Descrizione strutturale
Lezione11Design PatternIngegneria del Software 77
Descrizione comportamento
Lezione11Design PatternIngegneria del Software 78
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 79
<<Originator>>
Originator
+SetMemento (Memento m) <<setMemOp>>
+CreateMemento () <<createMemOp>>
<<Memento>>
Memento
+GetState () <<getStOp>>
+SetState () <<setStOp>>
- State <<stateProp>> - State <<statePropMem>>
<<Caretaker>>
Caretaker
MEM
Memento
Memento>=0
<<memRole>>
Specifica formale: comportamento
Lezione11Design PatternIngegneria del Software 80
m->GetState()
St:
m: Memento
SetMemento
State=St
CreateMemento
new Memento(State)
m: Memento
Activity diagrams
Specifica formale: comportamento
Lezione11Design PatternIngegneria del Software 81
CT: Caretaker O: Originator
CreateMemento ()<<createMemOp>>
M: Memento<<create>>
SetState () <<setStOp>>
SetMemento (M)<<setMemOp>> GetState ()
<<getStOp>>
Memento<<Caretaker>>
Caretaker<<Originator>>
Originator
<<Memento>>
Memento
class class
classSequence
diagram
Observer
• Esempio: mantenere coerenza vista con
cambiamenti oggetto rappresentato
Lezione11Design PatternIngegneria del Software 82
Descrizione strutturale
Lezione11Design PatternIngegneria del Software 83
Descrizione comportamento
Lezione11Design PatternIngegneria del Software 84
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 85
+ Attach (Observer) <<attachOp>>
+ Detach (Observer) <<detachOp>>
+ Notify () <<notifyOp>>
<<Subject>>
Subject
<<ConcreteSubject>>
ConcreteSubject
+ Update () <<updateOp>>
<<Observer>>
Observer
Observers
+ GetState () <<getStateOp>>
+ SetState (…) <<setStateOp>>
<<ConcreteObserver>>
ConcreteObserver
+ Update () <<updateOp>>
Subject
subjects
observers
Observer
Observer>=0, subjects>0, observers>0
<<obsRole>>
<<subjRole>>
Specifica formale: comportamento
Lezione11Design PatternIngegneria del Software 86
: ConcreteSubject
SetState ()Notify ()<<notifyOp>>
O: Observer
Update ()<<updateOp>>
GetState ()<<updateOp>>
<<setStateOp>>
subjects
O in Observersloop
<<ConcreteSubject>>
ConcreteSubject<<Observer>>
Observer
class class
Observer
State
• Esempio: gestione stati protocollo, sistema
risponde in modo diverso a stessi messaggi
Lezione11Design PatternIngegneria del Software 87
Descrizione strutturale
Lezione11Design PatternIngegneria del Software 88
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 89
<<Context>>
Context
+Request () <<reqOP>>
<<State>>
State
+Handle () <<handleOP>>
state
<<ConcreteState>>
ConcreteState
+Handle () <<concHandleOP>>
states
State>=0, states>0
State
Specifica formale: comportamento
Lezione11Design PatternIngegneria del Software 90
: Context
Request ()
<<reqOP>>
state: State
Handle ()
<<handleOP>>
State <<Context>>
Context<<State>>
State
classclass
Strategy
• Motivazione: situazioni in cui ci possono essere
diversi algoritmi per uno stesso problema. Scelta
dipende da varie circostanze. Non si vogliono
codificare tutte le scelte
• Esempio: gestione interruzioni di linea
Lezione11Design PatternIngegneria del Software 91
Descrizione strutturale
Lezione11Design PatternIngegneria del Software 92
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 93
<<Context>>
Context<<Strategy>>
Strategy
+OPSTR () <<strAlgOP>>
strategy
<<ConcreteStrategy>>
ConcreteStrategy
strategies
Strategy>=0, strategies>0, algInterface>0
Strategy
algInterface
Template method
• Motivazione: operazioni definite in termini astratti e
raffinate da implementazioni concrete
• Esempio: applicazione con diversi tipi di documenti
Lezione11Design PatternIngegneria del Software 94
Descrizione strutturale
Lezione11Design PatternIngegneria del Software 95
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 96
+TempMethod () <<tempMethod>>
+ PrimOP () <<primOP>>
<<AbstractClass>>
AbstractClass
primOperations
<<ConcreteClass>>
ConcreteClass
TemplateMethod
TemplateMethod>=0, primOperations>0,
subclasses>0
subclasses
Visitor
• Motivazione: esplorazione di strutture con
tipi diversi per eseguire operazioni diverse
• Esempio: attraversamento AST per controllo
dei tipi e generazione di codice
Lezione11Design PatternIngegneria del Software 97
Meccanismo dj base
Lezione11Design PatternIngegneria del Software 98
Descrizione strutturale
Lezione11Design PatternIngegneria del Software 99
Descrizione comportamento
Lezione11Design PatternIngegneria del Software 100
Specifica formale: struttura
Lezione11Design PatternIngegneria del Software 101
Specifica formale: comportamento
Lezione11Design PatternIngegneria del Software 102