Скачать презентацию Motifs de conception ou Design Patterns Laurent Ciarletta Скачать презентацию Motifs de conception ou Design Patterns Laurent Ciarletta

4033c97c58ef2b538a178504829bcd5d.ppt

  • Количество слайдов: 85

Motifs de conception ou “Design Patterns” Laurent Ciarletta @mines. inpl nancy. fr 1 Motifs de conception ou “Design Patterns” Laurent Ciarletta @mines. inpl nancy. fr 1

Bibliographie… w « A System of Pattern » Bushmann et All w « Design Bibliographie… w « A System of Pattern » Bushmann et All w « Design Patterns » Gamma et All w « Concurrent Programming in Java » D. Lea. w « Distributed Objects » Orfali et All w « Applying UML and Patterns » Larman w Présentations de Pascal Molli et Yannis Bres 2

Contexte 3 Contexte 3

Modélisation d’objets Des objectifs parfois antagonistes : • Encapsuler des données sans en empêcher 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 4

Modélisation d’applications Modéliser correctement une application : w Processus complexe w Expertise acquise au Modélisation d’applications Modéliser correctement une application : w Processus complexe w Expertise acquise au fil des expériences w Problèmes de conceptions récurrents : des Design Patterns Un (seminal) "livre de recettes" : Design Patterns, Elements of Reusable Object-Oriented Software E. Gamma, R. Helm, R. Johnson, J. Vlissides Addison Wesley 5

Becoming a Chess Master w First learn rules and physical requirements n e. g. Becoming a Chess Master w First learn rules and physical requirements n e. g. , names of pieces, legal movements, chess board geometry and orientation, etc. w Then learn principles n e. g. , relative value of certain pieces, strategic value of center squares, power of a threat, etc. w However, to become a master of chess, one must study the games of other masters n These games contain patterns that must be understood, memorized, and applied repeatedly w There are hundreds of these patterns 6

Becoming a Software Designer Master w First learn the rules n e. g. , Becoming a Software Designer Master w First learn the rules n e. g. , the algorithms, data structures and languages of software w Then learn the principles n e. g. , structured programming, modular programming, object oriented programming, generic programming, etc. w However, to truly master software design, one must study the designs of other masters n These designs contain patterns must be understood, memorized, and applied repeatedly w There are hundreds of these patterns 7

Patterns… w « Patterns help you build on the collective experience of skilled software Patterns… w « Patterns help you build on the collective experience of skilled software engineers. » w « They capture existing, well proven experience in software development and help to promote good design practice » w « Every pattern deals with a specific, recurring problem in the design or implementation of a software system » w « Patterns can be used to construct software architectures with specific properties… » 8

Software Architecture w A software architecture is a description of the subsystems and components Software Architecture w A software architecture is a description of the subsystems and components of a software system and the relationships between them. w Subsystems and components are typically specified in different views to show the relevant functional and non functional properties of a software system. w The software system is an artifact. It is the result of the software design activity. 9

Component w A component is an encapsulated part of a software system. A component Component w A component is an encapsulated part of a software system. A component has an interface. w Components serve as the building blocks for the structure of a system. w At a programming language level, components may be represented as modules, classes, objects or a set related functions. 10

Subsystems w A subsystem is a set of collaborating components performing a given task. Subsystems w A subsystem is a set of collaborating components performing a given task. A subsystem is considered a separate entity within a software architecture. w It performs its designated task by interacting with other subsystems and components… 11

Architectural Patterns w An architectural Pattern express a fundamental structural organization schema for software Architectural Patterns w 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. 12

Design patterns w A design pattern provides a scheme for refining the subsystems or Design patterns w 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. 13

Idioms w An Idiom is a low level pattern specific to a programming language. Idioms w 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. 14

Framework w A framework is a partially complete software (sub ) system that is Framework w 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. 15

Un Design Pattern Nom Exposé du problème Contexte de mise en œuvre, contraintes limitantes Un Design Pattern Nom Exposé du problème Contexte de mise en œuvre, contraintes limitantes Description de la solution proposée Conseils d’implémentation Exemple d’implémentation Conseils d’implémentation Confrontation avec d’autres Design Patterns Modèles parfois (souvent ? ) triviaux Relative standardisation du nommage des Design Patterns 16

Principales classes de Design Patterns de création • Création d’objets sans instanciation directe d’une Principales classes de Design 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 17

Les Design Patterns Class Creational Factory Method Abstract Factory Builder Prototype Singleton Scope Object Les Design Patterns Class Creational Factory Method Abstract Factory Builder Prototype Singleton Scope Object Purpose Structural Behavioral Adapter Interpreter Template Method Adapter Bridge Composite Decorator Facade Proxy Chain of Responsibility Command Iterator Mediator Memento Flyweight Observer State Strategy Visitor 18

Pattern Factory Method w Intent n n n Define an interface for creating an Pattern Factory Method w Intent n n n 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 19

Factory Method/Virtual Constructor w Applicability : Use when n n a class cannot anticipate Factory Method/Virtual Constructor w Applicability : Use when n n a class cannot anticipate the class of objects it must create a class wants its subclasses to specify the objects it creates 20

Structure 21 Structure 21

Factory method w Consequences n n Provide hooks for subclasses connects parallel class hierarchies Factory method w Consequences n n Provide hooks for subclasses connects parallel class hierarchies w Known uses n n n Mac. App, ET++ Class. View in smalltalk 80 MVC (controller creation) Orbix ORB for generating PROXY object 22

Abstract Factory Objectif : obtenir des instances de classes implémentant des interfaces connues, mais 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 23

Prototype Objectif : obtenir une instance d’un objet à partir d’une autre instance Exemple 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 24

Singleton Objectif : s’assurer qu’une seule instance d’un type spécifique existe dans le système 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 25

Adapter / Wrapper Objectif : obtenir un objet qui permet d’en utiliser un autre 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 26

Proxy / Surrogate Objectif : obtenir un objet qui agit comme intermédiaire dans la 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 ; … 27

Composite Objectif : manipuler indifféremment des objets atomiques ou des agrégats d’objets Exemple : 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 28

Decorator / Wrapper Objectif : ajouter à des instances spécifiques des comportements spécifiques Exemple Decorator / Wrapper Objectif : ajouter à des instances spécifiques des comportements spécifiques Exemple : bordure d’un composant graphique 29

Facade Objectif : fournir une interface simplifiée et limitée à un système complexe Exemple Facade Objectif : fournir une interface simplifiée et limitée à un système complexe Exemple : donner accès à des passes spécifiques d’un compilateur 30

Command Objectif : réifier une commande en un objet embarquant d’éventuels paramètres Exemple : 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 31

Command Pattern… w Encapsulate a request as an object, thereby letting you parameterize clients Command Pattern… w Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations. 32

Command Example 33 Command Example 33

Command Example 34 Command Example 34

Command Structure 35 Command Structure 35

Command Consequences 1. Command decouples the object that invokes the operation from the one 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. 36

Iterator Objectif : permettre d’itérer de manière générique sur les éléments d’une collection, quelle 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 37

Observer / Listener Objectif : permettre à un objet d’informer d’autres objets qu’il ne 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 38

Observer: Applicability w A change to one object requires changing an unknown set of Observer: Applicability w A change to one object requires changing an unknown set of others w Object should be able to notify others that may not be known at the beginning 39

Observer: Structure 40 Observer: Structure 40

Observer: Consequences w Abstract coupling between subject and observer w Support for broadcast communication Observer: Consequences w Abstract coupling between subject and observer w Support for broadcast communication w Hard to maintain 41

Observer View 42 Observer View 42

Observer w One to many dependency between objects: change of one object will automatically Observer w One to many dependency between objects: change of one object will automatically notify observers 43

Strategy / Policy Objectif : utiliser de manière non spécifique une collection d’algorithme proches Strategy / Policy Objectif : utiliser de manière non spécifique une collection d’algorithme proches Exemple : algorithmes de tris de collections de données 44

State Objectif : un objet qui change de comportement en fonction de son état State Objectif : un objet qui change de comportement en fonction de son état interne Exemple : une socket TCP (état non connectée, en attente de connection) 45

Visitor Objectif : découpler une structure des opérations sur cette structure Exemple : analyses/transformations Visitor Objectif : découpler une structure des opérations sur cette structure Exemple : analyses/transformations d’arbres de syntaxe abstraite dans un compilateur 46

Combiner des Patterns 47 Combiner des Patterns 47

48 48

Et encore 49 Et encore 49

Architectural Patterns… w From MUD to Structure… n Layers, Pipe and Filters, Blackboard w Architectural Patterns… w From MUD to Structure… n Layers, Pipe and Filters, Blackboard w Distributed Systems… n Broker, Pipe and Filters, Microkernel w Interactive Systems… n MVC, PAC w Adaptable Systems… n Microkernel, Reflection… 50

Model View Contoler (MVC) w The model contains the core functionality and data? w Model View Contoler (MVC) w The model contains the core functionality and data? w Views display information to the user. w Controllers handle user input. w A change propagation mechanism ensure consistency between user interface and the model. 51

MVC 52 MVC 52

MVC Structure 53 MVC Structure 53

MVC Structure 54 MVC Structure 54

MVC Structure 55 MVC Structure 55

 MVC Known Uses w Smalltalk w SWING w Etc… 56 MVC Known Uses w Smalltalk w SWING w Etc… 56

MVC benefits w Multiple views of the same model w Synchronized views: change propagation MVC benefits w Multiple views of the same model w Synchronized views: change propagation w Pluggable views and controllers w Exchangeability of ‘look and feel’ w Framework potential 57

MVC Liabilities w w w Increased complexity Potential for excessive number of updates Intimate MVC Liabilities w w w 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 w Difficulty of using MVC with modern user interface tools 58

Presentation Abstraction Control w PAC define a hierarchy of cooperating agents. w Each agent Presentation Abstraction Control w PAC define a hierarchy of cooperating agents. w Each agent consists of three components: presentation, abstraction, control. w Separates human computer interaction from its functional core and its communication with other agents… 59

PAC Example 60 PAC Example 60

PAC Example 61 PAC Example 61

Broker w Used to structure distributed software systems with decoupled components that interact by Broker w Used to structure distributed software systems with decoupled components that interact by remote service invocation. w A broker component is responsible for coordinating communication, such as forwarding request, as well as for transmitting result and exception. 62

And many others w Et beaucoup d’autres… 63 And many others w Et beaucoup d’autres… 63

Summary (C. Alexander) w It is possible to make building by stringing together patterns, Summary (C. Alexander) w 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. 64

Drawbacks of Patterns w w w Patterns do not lead to direct code reuse. Drawbacks of Patterns w w w 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. w Integrating patterns into a software development process is a human intensive activity. 65

Conclusion • Des solutions recettes adaptables pour des problèmes récurrents • Des propositions de 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 66

Exemples repris 67 Exemples repris 67

Composite Pattern w Compose objects into tree structures to represent part whole hierarchies. Composite Composite Pattern w Compose objects into tree structures to represent part whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. 68

Composite Example 69 Composite Example 69

Composite Example 70 Composite Example 70

Composite Structure 71 Composite Structure 71

Applying Composite on Command 72 Applying Composite on Command 72

Proxy Pattern w Provide a surrogate or placeholder for another object to control access Proxy Pattern w Provide a surrogate or placeholder for another object to control access to it. 73

Proxy Example 74 Proxy Example 74

Proxy Structure 75 Proxy Structure 75

Proxy benefits 1. remote proxy can hide the fact that an object resides in 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. 76

Adapter Pattern w Convert the interface of a class into another interface clients expect. Adapter Pattern w Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. 77

Adapter Example 78 Adapter Example 78

Adapter Structure 79 Adapter Structure 79

Visitor Pattern w Represent an operation to be performed on the elements of an Visitor Pattern w 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. 80

Visitor example 81 Visitor example 81

Visitor example 82 Visitor example 82

Visitor applicability w many distinct and unrelated operations need to be performed on objects Visitor applicability w 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 83

Visitor Structure 84 Visitor Structure 84

Visitor Consequences 1. Visitor makes adding new operations easy 2. A visitor gathers related 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 85