1 motifs de conception ou “design patterns” laurent ciarletta @mines.inpl-nancy.fr
TRANSCRIPT
2
Bibliographie…
« A System of Pattern » Bushmann et All « Design Patterns » Gamma et All « Concurrent Programming in Java » D. Lea. « Distributed Objects » Orfali et All « Applying UML and Patterns » Larman Présentations de Pascal Molli et Yannis Bres
3
Contexte
4
Modélisation d’objets
Des objectifs parfois antagonistes :• Encapsuler des données sans en empêcher l’accès• Trouver le bon niveau de granularité des objets• Limiter les dépendances entre objets• Concevoir des objets polyvalents, flexibles, réutilisables• Simplicité d’utilisation• Implémentation performante
5
Modélisation d’applications
Modéliser correctement une application : Processus complexe Expertise acquise au fil des expériences Problèmes de conceptions récurrents : des Design Patterns
Un (seminal) "livre de recettes" :Design Patterns, Elements of Reusable Object-Oriented SoftwareE. Gamma, R. Helm, R. Johnson, J. Vlissides - Addison Wesley
6
Becoming a Chess Master
First learn rules and physical requirements e.g., names of pieces, legal movements, chess board geometry
and orientation, etc. Then learn principles
e.g., relative value of certain pieces, strategic value of center squares, power of a threat, etc.
However, to become a master of chess, one must study the games of other masters
These games contain patterns that must be understood, memorized, and applied repeatedly
There are hundreds of these patterns
7
Becoming a Software Designer Master
First learn the rules e.g., the algorithms, data structures and languages of software
Then learn the principles e.g., structured programming, modular programming, object
oriented programming, generic programming, etc. However, to truly master software design, one must
study the designs of other masters These designs contain patterns must be understood,
memorized, and applied repeatedly There are hundreds of these patterns
8
Patterns…
« Patterns help you build on the collective experience of skilled software engineers. »
« They capture existing, well-proven experience in software development and help to promote good design practice »
« Every pattern deals with a specific, recurring problem in the design or implementation of a software system »
« Patterns can be used to construct software architectures with specific properties… »
9
Software Architecture
A software architecture is a description of the subsystems and components of a software system and the relationships between them.
Subsystems and components are typically specified in different views to show the relevant functional and non-functional properties of a software system.
The software system is an artifact. It is the result of the software design activity.
10
Component
A component is an encapsulated part of a software system. A component has an interface.
Components serve as the building blocks for the structure of a system.
At a programming-language level, components may be represented as modules, classes, objects or a set related functions.
11
Subsystems
A subsystem is a set of collaborating components performing a given task. A subsystem is considered a separate entity within a software architecture.
It performs its designated task by interacting with other subsystems and components…
12
Architectural Patterns
An architectural Pattern express a fundamental structural organization schema for software systems. It provides a set of predefined subsystems, their responsibilities, and includes rules and guidelines for organizing the relationships between them.
13
Design patterns
A design pattern provides a scheme for refining the subsystems or components of a software system, or the relation ships between them. It describes a commonly-recurring structure of communicating components that solves a general design problem within a particular context.
14
Idioms
An Idiom is a low-level pattern specific to a programming language. An idiom describes how to implement particular aspects of components or the relationships between them using the features of the given language.
15
Framework
A framework is a partially complete software (sub-) system that is intended to be instantiated. It defines the architecture for a family of (sub-) systems and provides the basic building blocks to create them. It also defines the places where adaptations for specific functionality should be made.
16
Un Design Pattern
NomExposé du problèmeContexte de mise en œuvre, contraintes limitantesDescription de la solution proposéeConseils d’implémentationExemple d’implémentationConseils d’implémentationConfrontation avec d’autres Design PatternsModèles parfois (souvent ?) triviauxRelative standardisation du nommage des Design Patterns
17
Principales classes de Design Patterns
Patterns de création• Création d’objets sans instanciation directe d’une classe
Patterns de composition• Composition de groupes d’objets
Patterns comportementaux• Modélisation des communications inter-objets et du flot de données
18
Les Design Patterns
PurposeCreational Structural Behavioral
Scope
ClassFactory Method Adapter Interpreter
Template Method
Object
Abstract FactoryBuilderPrototypeSingleton
AdapterBridgeCompositeDecoratorFacadeProxy
Chain of ResponsibilityCommandIteratorMediatorMementoFlyweightObserverStateStrategyVisitor
19
Pattern Factory Method
Intent Define an interface for creating an object, but let
sub-classes decide which class to instantiate let a class defer instantiation to subclasses Also known as Virtual Constructor
20
Factory Method/Virtual Constructor
Applicability : Use when a class cannot anticipate the class of objects it must
create a class wants its subclasses to specify the objects it
creates
21
Structure
Produit
ProduitConcret
Facteur
Fabrication()UneOperation()
FacteurConcret
Fabrication()
produit=Fabrication()
return new ProduitConcret()
22
Factory method
Consequences Provide hooks for subclasses connects parallel class hierarchies
Known uses MacApp, ET++ ClassView in smalltalk80 MVC (controller
creation) Orbix ORB for generating PROXY object
23
Abstract Factory
Objectif : obtenir des instances de classes implémentant des interfaces connues, mais en ignorant le type réel de la classe obtenue
Exemple : une application gérant des documents polymorphes générateur de compo-sants graphiques supportant une multitude de look-and-feels
24
Prototype
Objectif : obtenir une instance d’un objet à partir d’une autre instance
Exemple : drag-and-drop de composants inconnus avec touche Ctrl enfoncée
25
Singleton
Objectif : s’assurer qu’une seule instance d’un type spécifique existe dans le système et fournir l’accès à cet objet
Exemple : un spooler d’impression
26
Adapter / Wrapper
Objectif : obtenir un objet qui permet d’en utiliser un autre en conformité avec une certaine interface
Exemple : mise en "conformité" de composants d’origines diverses
27
Proxy / Surrogate
Objectif : obtenir un objet qui agit comme intermédiaire dans la communication avec un autre objet (un "passeur d’ordre")
Exemples : un objet qui reporte les opérations coûteuses au moment où on utilise réellement les résultats de ces opérations (chargement d’une image à la fin d’un document, …) ; un objet qui transforme une collection en lecture-seule ; …
28
Composite
Objectif : manipuler indifféremment des objets atomiques ou des agrégats d’objets
Exemple : une application manipulant des formes graphiques et des compositions de ces formes
29
Decorator / Wrapper
Objectif : ajouter à des instances spécifiques des comportements spécifiques
Exemple : bordure d’un composant graphique
30
Facade
Objectif : fournir une interface simplifiée et limitée à un système complexeExemple : donner accès à des passes spécifiques d’un compilateur
31
Command
Objectif : réifier une commande en un objet embarquant d’éventuels paramètres
Exemple : uniformiser les différentes méthodes de commande d’un système et gérer l’undo et le redo
32
Command Pattern…
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
33
Command Example
34
Command Example
35
Command Structure
36
Command Consequences
1. Command decouples the object that invokes the operation from the one that knows how to perform it.
2. Commands are first-class objects. They can be manipulated and extended like any other object.
3. It's easy to add new Commands, because you don't have to change existing classes.
37
Iterator
Objectif : permettre d’itérer de manière générique sur les éléments d’une collection, quelle que soit la nature des éléments ou de la collection
Exemple : trop naze, on le fait tous les jours
38
Observer / Listener
Objectif : permettre à un objet d’informer d’autres objets qu’il ne connaît pas de l’évolution de son état interne
Exemple : un bouton à la suite d’un click
39
Observer: Applicability
A change to one object requires changing an unknown set of others
Object should be able to notify others that may not be known at the beginning
40
Observer: Structure
41
Observer: Consequences
Abstract coupling between subject and observer Support for broadcast communication Hard to maintain
42
Observer View
Observer
update(o : Observable, arg : Object) : void
(from util)
<<Interface>>
DieView
DieView(die : Die)update(o : Observable, arg : Object) : void
PlayerView
PlayerView(player : Player)update(o : Observable, arg : Object) : void
43
Observer
One-to-many dependency between objects: change of one object will automatically notify observers
44
Strategy / Policy
Objectif : utiliser de manière non spécifique une collection d’algorithme proches
Exemple : algorithmes de tris de collections de données
45
State
Objectif : un objet qui change de comportement en fonction de son état interneExemple : une socket TCP (état non connectée, connectée, en attente de
connection)
46
Visitor
Objectif : découpler une structure des opérations sur cette structureExemple : analyses/transformations d’arbres de syntaxe abstraite dans un
compilateur
47
Combiner des Patterns
48
49
Et encore
50
Architectural Patterns…
From MUD to Structure… Layers, Pipe and Filters, Blackboard
Distributed Systems… Broker, Pipe and Filters, Microkernel
Interactive Systems… MVC, PAC
Adaptable Systems… Microkernel, Reflection…
51
Model-View-Contoler (MVC)
The model contains the core functionality and data?
Views display information to the user. Controllers handle user input. A change propagation mechanism ensure
consistency between user interface and the model.
52
MVC
53
MVC Structure
54
MVC Structure
55
MVC Structure
56
MVC Known Uses
Smalltalk SWING Etc…
57
MVC benefits
Multiple views of the same model Synchronized views: change propagation Pluggable views and controllers Exchangeability of ‘look and feel’ Framework potential
58
MVC Liabilities
Increased complexity Potential for excessive number of updates Intimate connection between view and controller Close coupling of views and controllers to a model Inefficiency of data access in view Inevitability of change to view and controller when
porting Difficulty of using MVC with modern user-interface
tools
59
Presentation-Abstraction-Control
PAC define a hierarchy of cooperating agents. Each agent consists of three components:
presentation, abstraction, control. Separates human computer interaction from its
functional core and its communication with other agents…
60
PAC Example
61
PAC Example
62
Broker
Used to structure distributed software systems with decoupled components that interact by remote service invocation.
A broker component is responsible for coordinating communication, such as forwarding request, as well as for transmitting result and exception.
63
And many others
Et beaucoup d’autres…
64
Summary (C. Alexander)
It is possible to make building by stringing together patterns, in a rather loose way. A building made like this, is an assembly of patterns. It is not dense. It is not profound. But it is also possible to put patterns together in such way that many patterns overlap in the same physical space: the building is very dense; it has many meanings captured in a small space; and through this density, it becomes profound.
65
Drawbacks of Patterns
Patterns do not lead to direct code reuse. Individual Patterns are deceptively simple. Composition of different patterns can be very
complex. Teams may suffer from pattern overload. Patterns are validated by experience and discussion
rather than by automated testing. Integrating patterns into a software development
process is a human intensive activity.
66
Conclusion
• Des solutions-recettes adaptables pour des problèmes récurrents
• Des propositions de bases pour l’élaboration de solutions plus complexes
• Modèles parfois (souvent ?) triviaux
67
Exemples repris
68
Composite Pattern
Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
69
Composite Example
70
Composite Example
71
Composite Structure
72
Applying Composite on Command
73
Proxy Pattern
Provide a surrogate or placeholder for another object to control access to it.
74
Proxy Example
75
Proxy Structure
76
Proxy benefits
1. remote proxy can hide the fact that an object resides in a different address space.
2. A virtual proxy can perform optimizations such as creating an object on demand.
3. Both protection proxies and smart references allow additional housekeeping tasks when an object is accessed.
77
Adapter Pattern
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
78
Adapter Example
79
Adapter Structure
80
Visitor Pattern
Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
81
Visitor example
82
Visitor example
83
Visitor applicability
many distinct and unrelated operations need to be performed on objects in an object structure, and you want to avoid "polluting" their classes with these operations
84
Visitor Structure
85
Visitor Consequences
1. Visitor makes adding new operations easy
2. A visitor gathers related operations and separates unrelated ones
3. Adding new Concrete Element classes is hard
4. Visiting across class hierarchies
5. Accumulating state.
6. Breaking encapsulation