© 2002-2003 Riccardo Solmi 1
TITLE
Laboratorio di Sistemi Software Design Patterns 1
Luca Padovani (A-L) Riccardo Solmi (M-Z)
2
Indice degli argomenti
§ Tipi di Design Patterns
• Creazionali, strutturali, comportamentali
§ Design Patterns
• Factory Method, Strategy, State, Decorator
• Composite, Iterator, Visitor
• Template Method, Abstract Factory, Builder, Singleton
• Proxy, Adapter, Bridge, Facade
• Mediator, Observer, Chain of Responsibility
• Command, Prototype
© 2002-2003 Riccardo Solmi 3
Bibliografia
§ UML
• Linguaggio per modellare un Sistema Software.
§ Design Patterns – Elements of Reusable Object-Oriented Software
• Catalogo di patterns di progettazione
§ Refactoring – Improving the Design of Existing Code
• Catalogo di operazioni di Refactoring
§ Eclipse IDE + UML Plugin
• Ambiente di programmazione che supporta refactoring e UML.
§ Trovate tutto nelle pagine web relative a questo corso:
• http://www.cs.unibo.it/~solmi/teaching/labss_2002-2003.html
• http://www.cs.unibo.it/~lpadovan/didattica.html
Ricevimento
§ Metodo 1: il newsgroup
• Avete a disposizione un newsgroup:
unibo.cs.informatica.paradigmiprogrammazione
• Utilizzatelo il più possibile; se nessuno risponde in due-tre giorni, risponderà uno dei docenti
• Valuteremo anche la partecipazione al newsgroup
§ Metodo 2: subito dopo le lezioni
• siamo a vostra disposizione per chiarimenti
• in aula e alla lavagna, in modo da rispondere a tutti
§ Metodo 3: ricevimento su appuntamento
• Scrivete a [email protected] (A-L)
o a [email protected] (M-Z)
© 2002-2003 Riccardo Solmi 5
Alcuni concetti
§ Incapsulare
• Racchiudere in modo da mostrare all’esterno solo quello che voglio. Gioco su package, classi e visibilità.
§ Delegare
• Si dice che un metodo delega un altro …
• NB. In Java si può solo inoltrare una chiamata this resta legato all’oggetto chiamato.
§ Inoltrare (forwards )
§ Indirezione
• Ogni volta che prima di fare la cosa richiesta ne faccio un’altra (che in genere mi serve per capire come farla).
• Esempi: delega e codice condizionale
6
Alcuni concetti /2
§ Staticamente/dinamicamente
• Dinamicamente significa che si verifica durante
l’esecuzione (runtime) altrimenti è statico (compile time o initialization time).
§ Statefull/stateless class(object)
• Con o senza campi.
§ Accoppiato
• Una classe/interfaccia è accoppiata ad un altra quando
contiene un suo riferimento. Esempio : chiamata con
parametro di un tipo non primitivo.
© 2002-2003 Riccardo Solmi 7
Design Patterns
§ Definizione
• Un Design Pattern descrive un problema ricorrente di progettazione e uno schema di soluzione per risolverlo.
• NB Il termine Design nel nome non significa che riguardano solo la progettazione
§ Serve a …
• Progettare e implementare il Software in modo che abbia la flessibilità e le capacità di evolvere desiderate
• Dominare la complessità di un Sistema Software
§ Catalogo
• Ogni Design Pattern ha un nome, un campo di applicabilità, uno schema di soluzione e una descrizione delle
conseguenze della sua applicazione.
Esempi di
Design Patterns
© 2002-2003 Riccardo Solmi 9
Design Patterns
§ Design Patterns : progettare anticipando i cambiamenti
• Prima si progetta il Software poi lo si implementa.
• Massimizzare il riuso (senza ricompilazione)
• La compatibilità all’indietro è spesso un obiettivo.
• Assumo di poter controllare solo una parte del codice sorgente.
• Progettare il Sistema in modo da anticipare i nuovi requisiti e i cambiamenti a quelli esistenti.
10
Design Patterns
§ Uso Design Patterns per le esigenze attuali
• Si riduce enfasi sulla progettazione iniziale
• Mi basta progettare una soluzione ragionevole non la migliore soluzione.
• Continuo a chiedermi come evolverà il sistema ma mi basta sapere di poter aggiungere un certo tipo di flessibilità con il Refactoring
§ Incorporare Design nei sorgenti
• Le scelte progettuali e le dipendenze devono essere il più possibile espresse nei sorgenti
• I commenti non sono un deodorante per rendere accettabile
un codice illeggibile
© 2002-2003 Riccardo Solmi 11
Rischi e limiti dei Design Patterns
§ Esistono dei trade -off
• Non esiste una combinazione di Patterns che mi dà il massimo di flessibilità e di facilità di evolvere.
• Un Design Pattern facilita alcuni sviluppi futuri a scapito di altri.
• Cambiare una scelta progettuale è costoso
§ Rischio di sovra-ingegnerizzare
• Il codice diventa più flessibile e sofisticato di quanto serve.
• Quando scelgo i Patterns prima di iniziare ad implementare.
• Quando introduco i Patterns troppo presto.
§ Costo computazionale
• La flessibilità di una soluzione costa ed è accompagnata da una maggiore complessità.
• Usare un Design Pattern per esigenze future è un costo
Limiti OO evidenziati dai Design Patterns
§ Identità degli oggetti (Object Schizophrenia)
• Spesso una entità del dominio viene rappresentata da un insieme di classi dell’applicazione
• Problema del significato di this.
§ Incapsulamento dei dati
• La scomposizione di una entità in più classi mi obbliga a ridurre l’incapsulamento dei dati.
§ Rappresentazione indiretta
• Dato un programma, non è facile stabilire quali Design Pattern sono stati applicati.
• Parte delle informazioni di progettazione sono perse.
© 2002-2003 Riccardo Solmi 13
Dipendenze nel codice
§ Scrivere un programma introduce dipendenze
• Comprendere le dipendenze che si introducono in modo da scegliere consapevolmente i Design Pattern.
• Le dipendenze contenute in una classe/interfaccia consistono nell’insieme dei riferimenti (statici) ad altre classi/interfacce.
• I design pattern vengono classificati in base al tipo di dipendenze su cui agiscono in: creazionali, strutturali, comportamentali.
• Esempi di dipendenze: istanziazione oggetti, campi e metodi, variabili e parametri di tipi non primitivi
14
Design Patterns Creazionali
§ Astraggono il processo di istanziazione
• Nascondo i costruttori e introduco dei metodi al loro posto
§ Conseguenze:
• Incapsulano la conoscenza delle classi concrete usate
• Nascondono il modo in cui le istanze di queste classi vengono create e assemblate
• Espongono interfacce al posto di tipi concreti
© 2002-2003 Riccardo Solmi 15
Design Patterns Strutturali
§ Descrivono come comporre classi e oggetti in strutture più grandi
• Si dividono in: basati su classi e su oggetti
• I primi usano l’ereditarietà (statica)
• I secondi la composizione (anche dinamica)
§ Conseguenze
• Aggiungono un livello di indirezione per disaccoppiare le due interfacce.
Design Patterns comportamentali
§ Riguardano algoritmi e l’assegnamento di responsabilità tra oggetti
• Descrivono pattern di comunicazione tra oggetti.
• Per distribuire il comportamento usano l’ereditarietà o la composizione.
§ Conseguenze
• Alcuni incapsulano il comportamento in modo da poterlo variare anche dinamicamente
• Disaccoppiano il chiamante e il chiamato aggiungendo un
livello di indirezione.
© 2002-2003 Riccardo Solmi 17
Factory Method
§ Intent
• Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
§ Applicability
• 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 localize the knowledge of which helper subclass is the delegate.
18
Factory Method /2
§ Structure
§ Participants
• Product (Document)
• defines the interface of objects the factory method creates.
• ConcreteProduct (MyDocument)
• implements the Product interface.
• Creator (Application)
• declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object.
• may call the factory method to create a Product object.
• ConcreteCreator (MyApplication)
• overrides the factory method to return an instance of a ConcreteProduct
© 2002-2003 Riccardo Solmi 19
FactoryMethod /3
§ Collaborations
• Creator relies on its subclasses to define the factory method so that it returns an instance of the appropriate
ConcreteProduct.
§ Consequences
• The code only deals with the interface; therefore it can work with any user-defined concrete classes.
• Provides hooks for subclasses
• Connects parallel class hierarchies
Factory Method example 1
§ JComponent
© 2002-2003 Riccardo Solmi 21
Factory Method example 2
§ The code only deals with the interface; therefore it can work wi th any user-defined concrete classes.
22
Factory Method example 3
§ Connects parallel class hierarchies
© 2002-2003 Riccardo Solmi 23
Factory Method questions
§ How does Factory Method promote loosely coupled code?
Strategy
§ Intent
• Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
§ Applicability
• Many related classes differ only in their behavior. Strategies provide a way to configure a class with one of many
behaviors.
• You need different variants of an algorithm.
• An algorithm uses data that clients shouldn't know about.
• Instead of many conditionals.
© 2002-2003 Riccardo Solmi 25
Strategy /2
§ Structure
§ Participants
• Strategy
• declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy .
• ConcreteStrategy
• implements the algorithm using the Strategy interface
• Context
• is configured with a ConcreteStrategy object.
• maintains a reference to a Strategy object.
• may define an interface that lets Strategy access its data
26
Strategy /3
§ Collaborations
• Strategy and Context interact to implement the chosen algorithm. A context may pass data or itself to the Strategy.
• A context forwards requests from its clients to its strategy.
• Clients usually create and pass a ConcreteStrategy to the context;
thereafter, they interact with the context exclusively.
§ Consequences
• Families of related algorithms.
• An alternative to subclassing. Vary the algorithm independently of its context even dynamically.
• Strategies eliminate conditional statements.
• A choice of implementations (space/time trade-offs).
• Clients must be aware of different Strategies.
• Communication overhead between Strategy and Context.
• Increased number of objects (stateless option).
© 2002-2003 Riccardo Solmi 27
Strategy example 1
§ Sorting Strategy
Strategy example 2
§ To define different algorithms
© 2002-2003 Riccardo Solmi 29
Strategy questions
§ What happens when a system has an explosion of Strategy objects? Is there some way to better manage these strategies?
§ Is it possible that the data required by the strategy will not be available from the context's interface? How could you remedy this potential problem?
30
State
§ Intent
• Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
§ Applicability
• An object's behavior depends on its state, and it must change its behavior at run-time depending on that state.
• Operations have large, multipart conditional statements that depend on the object's state. This state is usually represented by one or more enumerated constants. Often, several
operations will contain this same conditional structure.
© 2002-2003 Riccardo Solmi 31
State /2
§ Structure
§ Participants
• Context
– defines the interface of interest to clients.
– maintains an instance of a ConcreteState subclass that defines the current state.
• State
– defines an interface for encapsulating the behavior associated with a particular state of the Context.
• ConcreteState subclasses – each subclass implements a
behavior associated with a state of the Context.
State /3
§ Collaborations
• Context delegates state-specific requests to the current ConcreteState object.
• A context may pass itself as an argument to the State object handling the request.
• Context is the primary interface for clients.
• Either Context or the ConcreteState subclasses can decide
which state succeeds another and under what circumstances.
© 2002-2003 Riccardo Solmi 33
State /4
§ Consequences
• It localizes state-specific behavior and partitions behavior for different states.
• It makes state transitions explicit.
• State objects can be shared.
§ Implementation
• Who defines the state transitions?
• Creating and destroying State objects
• A table-based alternative
34
State example 1
§ Queue
© 2002-2003 Riccardo Solmi 35
State example 2
§ Network connection
State example 3
§ Drawing tool
© 2002-2003 Riccardo Solmi 37
Decorator or Wrapper
§ Intent
• Attach additional responsibilities to an object dynamically.
Decorators provide a flexible alternative to subclassing for extending functionality.
§ Applicability
• to add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects.
• for responsibilities that can be withdrawn.
• when extension by subclassing is impractical or not allowed
38
Decorator /2
§ Structure
§ Participants
• Component
• defines the interface for objects that can have responsibilities added to them dynamically
• ConcreteComponent
• defines an object to which additional responsibilities can be attached
• Decorator
• maintains a reference to a Component object and defines an interface that conforms to Component's interface
• ConcreteDecorator
• adds responsibilities to the component
© 2002-2003 Riccardo Solmi 39
Decorator /3
§ Collaborations
• Decorator forwards requests to its Component object. It may optionally perform additional operations before and after forwarding the request
§ Consequences
• More flexibility than static inheritance.
• Avoids feature-laden classes high up in the hierarchy.
• A decorator and its component aren’t identical.
• Lots of little objects.
§ Implementation
• Keeping Component classes lightweight.
• Changing the skin of an object versus changing its guts.
Decorator example 1
§ String Decorator
© 2002-2003 Riccardo Solmi 41
Decorator example 2
§ To decorate an individual objects
42
Decorator example 3
§ Adding responsibilities to streams
© 2002-2003 Riccardo Solmi 43