Design Patterns Dr. Uwe Assmann PELAB (Slides derived from Walter F. Tichy, Universität Karlsruhe, Germany, Used by permission) Introduction n What is a Design Pattern? n For what can they be used? n How does it look like? n Literature: n „Design Patterns”, Gamma et al, Addison Wesley,1995 n „A System of Patterns”, Buschmann et al, Wiley, 1995. Part II from 2000 n „Pattern Languages of Program Design”, Conferences, AddisonWesley, 1995,... n „Software Architecture”, Shaw & Garlan, Prentice Hall, 1996. n “Object-oriented Design and Patterns” W. Pree, 1995, AddisionWesley n Special PhD Course Design Patterns (running now) 2 Definition n A Design Pattern is a description of a standard solution for a standard problem in design. n Goal: Reuse of design information n A pattern must not be “new”! 3 Alexander’s Laws on Beauty n Christopher Alexander “The timeless way of building” n a book of the century: A MUST n Hunting for the “Quality without a name” n Patterns grasp centers of beauty n You have a language for beauty, consisting of patterns n dependent on culture n Beauty cannot be invented but must be combined/generated by patterns from a pattern language n Alexander means “composition” 4 Example: Model/View/Controller (MVC) MVC is a agglomeration of classes to control a user interface and a data structure (from Smalltalk) n n n : Data structure or object, invisible Representation(s) on the screen Encapsulates reactions on inputs of users, couples model and views -ODEL 6IEW : : #ONTROLLER MVC is a complex design pattern and combines the simpler ones compositum, strategy, observer. 5 Views as Observer 7INDOW x y z a 60 50 80 7INDOW b 30 30 10 c 10 20 10 a b a=50% b=30% c=20% Model 6 7INDOW c Model/View/Controller Relation between model and views is grasped by the design pattern /BSERVER. n Views may register at the model (observers). n They are notified if the model changes. Then, every view updates itself by accessing the data of the model. n Views are independent of each other. The model does not know how views visualize it. n /BSERVER decouples strongly. 7 Pattern 2: Compositum may be NESTED (#OMPOSITUM) n Example: object inspector in debuggers n Compositum requires that 6IEWS n The class CompositeView is a subclass of View n Can be used in the same way as View 8 Pattern 3: Strategy The relation between CONTROLLER and VIEW is a 3TRATEGY pattern n There may be different control strategies n Lazy or eager update of views n Menu or keyboard input n A view may select subclasses of #ONTROLLER even dynamically n No other class changes 9 Structure for Design Pattern n There are several formats n Gof (Gamma Gang of Four) n Alexandrian format n Name (incl. Synonyms) n Task and Context n Solution n Structure (Components, Relations): UML class or object diagram n Interactions und Consequences: interaction diagrams n Implementation (code examples) 10 The GoF Template 0ATTERN .AME 3COPE 0URPOSE The pattern’s name conveys the essence of the pattern succinctly. A good name is vital, because it will become part of your design vocabulary. )NTENT A short statement that answers the following questions: What does the design pattern do? What is its rationale and intent? What particular design issue or problem does it address? !LSO +NOWN !S Other well-known names for the pattern, if any. -OTIVATION A scenario that illustrates a design problem and how the class and object structures in the pattern solve the problem. The scenario will help you understand the more abstract description of the pattern that follows. 11 The GoF Template !PPLICABILITY What are the situations in which the design pattern can be applied? What are examples of poor designs that the pattern can address? How can you recognize these situations? 3TRUCTURE A graphical representation of the classes in the pattern. 0ARTICIPANTS The classes and/or objects participating in the design pattern and their responsibilities. #OLLABORATIONS How the participants collaborate to carry out their responsibilities. 12 The GoF Template #ONSEQUENCES How does the pattern support its objectives? What are the trade-offs and results of using the pattern? What aspect of system structure does it let you vary independently? )MPLEMENTATION What pitfalls, hints, or techniques should you be aware of when implementing the pattern? Are there language-specific issues? 3AMPLE #ODE AND 5SAGE Code fragments that illustrate how you might implement the pattern in C++ or Smalltalk. +NOWN 5SES Examples of the pattern found in real systems. We include at least two examples from different domains. 2ELATED 0ATTERNS What design patterns are closely related to this one? What are the important differences? With which other patterns should this one be used? 13 A Pattern... n n n n n n n n n n n n n 14 Describes a single kind of problem. Describes the context in which the problem occurs. Describes the solution as a constructable software entity. Describes design steps or rules for constructing the solution. Describes the forces leading to the solution. Describes evidence that the solution optimally resolves forces. Describes details that are allowed to vary, and those that are not. Describes at least one actual instance of use. Describes evidence of generality across different instances. Describes or refers to variants and subpatterns. Describes or refers to other patterns that it relies upon. Describes or refers to other patterns that rely upon this pattern. Relates to other patterns with similar contexts, problems, or solutions. Purpose Design Pattern • Improve communication in teams • • • Abstracts design concepts • • • • Patterns are “mini-frameworks” Documentation May be used to capture information in reverse engineering Improvement of the state of the art of software engineering • • • • Between clients and programmers Between designers, implementers and testers A “software engineer” without the knowledge of patterns is a programmer Fix a glossary for software engineering Prevent re-invention of well-known solutions Improve code quality and structure 15 Design Pattern Categories n A classification is hard ù several are around n "ASIC PATTERNS n $ATA PATTERNS n n characterize simple collaboration scenarios in class graphs, sequence diagrams, or other diagrams. n Are used to form larger patterns characterize state of a set of objects and their responsibilities #REATIONAL 0ATTERNS determine how objects and object families are allocated divide systems into subsystems such that these can be exchanged independently n #OMMONALITY PATTERNS condense common parts of classes into new classes n #ONTROL FLOW PATTERNS "EHAVIORAL PATTERNS describe common control flow situations 16 #OUPLING PATTERNS 3TRUCTURAL PATTERNS Relations between Patterns #REATION PATTERNS "UILDER #OUPLING PATTERNS #ONTROL FLOW PATTERNS )NTERPRETER ,AYERS 3TRATEGY 0ROTOTYPE 6ISITOR &ACADE )TERATOR #HAIN/F ! BSTRACT &ACTORY /BSERVER 2ESPONSIBILITY "RIDGE &ACTORY-ETHOD #OMMAN 4EMPLATE /BJECTIFIER #OMPOSITUM 0ROXY 3INGLETON -ETHOD -EMENTO ! DAPTER -EDIATOR 'LUE &LYWEIGHT $ECORATOR "ASIC PATTERNS $ATA PATTERNS Overview Patterns n n n n n n n n n n n n "ASIC PATTERNS TemplateMethod: Vary the algoritm in a subclass Objectifier: Delegate behavior to special object Mediator: Object to encapsulate communication Decorator: Dynamic Extension of classes Proxy: Representant for remote objects Compositum: Part/Whole hierarchies Adapter: Adapt an interface to another $ATA PATTERNS Singleton: globally unique objects Flyweight: Space optimizations by representants Memento: Snapshot of state • • • • • • • • • #OUPLING 0ATTERNS Repository: central scratchpad Facade: encapsulating class for subsystem Layers: layered facades Bridge: decouple abstraction from implementation Observer: event based communication, dynamic Event channel: channel of observers Pipe: stream oriented communication Framework: #ONTROL FLOW BEHAVIORAL • Visitor: Decouple iteration over tree from actions ChainOfResponsibility: cascaded delegation Commad: reified command procedure Blackboard: organized repository Strategy: algorithm family Iterator: iteration without knowing internals Interpreter PATTERNS • • • • • • #REATIONAL 0ATTERNS • • • • 18 • FactoryMethod: Vary allocation in subclass Abstract Factory: Allocation of object family Builder:Incremental allocation of complex structured object Prototype: Clone an object Design Pattern Catalogue Basic Patterns n According to [W. Zimmer: Frameworks und Design Pattern, PhD 1997 Universität Karlsruhe] Design Pattern can be build from the following basic ones: n n n n n n n n TemplateMethod Objectifier (Delegation) Mediator Glue Decorator Proxy Compositum Adapter n Data Patterns n Singleton (singleton) n Flyweight n Memento 20 Template Method !BSTRACT#LASS TemplateMethod() PRIMITIVE/PERATION PRIMITIVE/PERATION ... primitiveOperation1(); ... primitiveOperation2(); ... #ONCRETE#LASS primitiveOperation1() primitiveOperation2() Define the skeleton of an algorithm (template method) Delegate parts to HOOK METHODS that are filled by subclasses Allows to vary behavior. 21 Template Method n Separate invariant from variant parts of an algorithm n Factor out common code into superclasses n Avoid code replacement n Control extensions by only allowing “hook methods” 22 Objectifier (Delegation Object) n n n n n n Reify a method by an object Delegate the behavior of the method to the object Vary the delegatee Factorization Varying behavior Used with: Bridge, Builder, Command, Iterator, Observer, State, Strategy, Visitor. 23 Mediator n Mediators encapsulate communication n Partners can register with the mediator and do not know with whom they talk n Communication can be varied dynamically 24 Mediator Mediator -EDIATOR #ONCRETE-EDIATOR #OLLEAGUE #ONCRETE#OLLEAGUE #ONCRETE#OLLEAGUE Typical Object Structure: !#OLLEAGUE !#ONCRETE-EDIATOR !#OLLEAGUE Mediator Mediator !#OLLEAGUE Mediator !#OLLEAGUE Mediator 25 Example Mediator n Many dependencies between parts of a window n Different widgets have different dependencies n Encapsulate behavior in a mediator that mediates between widgets n Spare class factorization n Widgets can be registered/deregistered dynamically n Flexible, but anonymous communication 26 Example Mediator Decoupling windows from text fields Mediator $IALOGUE-EDIATOR showDialog() 7IDGET changed() CREATE7IDGETS Mediator.widgetChanged(this) WIDGET#HANGED 7IDGET ,IST"OX liste 4EXT$IALOGUE-EDIATOR createWidgets() widgetChanged(Widget) )NPUT&IELD select() field 27 Proxy 3UBJECT #LIENT OPERATION 2EAL3UBJECT 0ROXY operation() ... operation() ... realSubject ... realSubject.operation() Hide the access to a real subject by a representant 28 Proxy n References instead of values n Protocol proxy: counts references (reference-counting garbage collection n Indirection proxy: assembles ALL references to an object to make it replaceable n Remote proxy: representant of a remote object n Caching proxy: caches values which had been loaded from the subject n Remote n Loading lazy on demand n Firewall: protection proxy 29 Adapter (Wrapper) #LIENT 'OAL#LASS !DAPTED#LASS OPERATION specificOperation() Can also be interface (Implementation) !DAPTER operation() specificOperation() Adapts an interface to a client May use multiple inheritance, but need not 30 Adapter (2) #LIENT 'OAL !DAPTIERTE#LASS OPERATION spezificOperation() adapted Object !DAPTER operation() adaptedObject.spezificOperation() Without Multiple Inheritance, but object adapter 31 %XAMPLE 5SE OF AN %XTERNAL #LASS ,IBRARY $RAWING%DITOR 'RAFIC/BJECT FRAMEW CREATE-ANIPULATOR 4EXT$ISPLAY largeness() ,INIE 4EXT frame() createManipulator() frame() createManipulator() return text.largeness() return new TextManipulator 32 Compositum Part/Whole hierarchies, e.g., nested graphic objects A0ICTURE A0ICTURE A0ICTURE A,INE A,INE A2ECTANGLE A2ECTANGLE common operations: draw(), move(), delete(), scale() 33 Structure Compositum #LIENT #OMPONENT COMMON/PERATION add(Component) remove(Component) getType(int) 34 } ,EAF #OMPOSITUM commonOperation() commonOperation() add(Component) remove(Component) getType(int) Pseudo implementations childObjects for all g in childObjects g.operation() Compositum n Class Compositum contains a container for the child objects n For iterations on hierarchies 35 Data Patterns Memento 36 Flyweight Singleton Structure for Singleton 3INGLETON static Singleton() private Singleton (first: bool) operation() getDaten() if uniqueInstance == null then uniqueInstance = new Singleton (true) return uniqueInstance static uniqueInstance data Assure one globally unique object of a class 37 Flyweight n Set of objects is very large n State can be moved from object to external memory (extrinsic state) n Identity of objects can be neglected n Introduce flyweight objects 38 Structure for Flyweight &LYWEIGHT&ACTORY &LYWEIGHT Flyweighte getFlyweight(key) OPERATIONEXTRINSIC3TATE if (Flyweighte[key] exists){ return Flyweight[key]; } else { create new Flyweight; add to Flyweight; return it; } #ONCRETE&LYWEIGHT 3EPARATELY5SED #ONCRETE&LYWEIGHT operation(extrinsicState)) operation(extrinsicState)) intrinsicState gesamtState #LIENT 39 Representants with minimal space Example Flyweight Object modeling for characters in editor Column Row e 40 Row x a a Row m p e l a b c d e f g h i j k l m n o p q r s t u v w x y z Set of Flyweights Memento Extensionalize state of object #LIENT -EMENTO restore(Memento m) createMemento() getState() setState() State State return new Memento(State) memento #ONTAINER State = m.getState() 41 Example Memento Breakpoints and Undo in editors, debuggers: Rectangles should stay linked If they are moved. 42 Undo might be wrong if state Is not sufficiently memorized Coupling (Structural) Patterns n n n n Observer Bridge (Adapter) Facade 43 Observer (Publisher/Subscriber) Observer 7INDOW x y z a 60 50 80 7INDOW b 30 30 10 7INDOW c 10 20 10 a b c a=50% b=30% c=20% Subject 44 Notify on change Queries Structure Observer Observer 3UBJECT /BSERVER UPDATE REGISTER/BSERVER UNREGISTER /BSERVER for all b in Observer { b.update () } NOTIFY #ONCRETER/BSERVER Subject #ONCRETES3UBJECT ObserverState = Subject.getState() update () getState() setState() ObserverState return SubjectState SubjectState 45 Sequence Diagram Observer aConcreteSubject aConcreteObserver anotherConcreteObserver () REGISTER () SET3TATE () NOTIFY () UPDATE N () GET3TATE () UPDATE N () GET3TATE 46 Observer n Loose coupling in communication n Observers decide what happens n n n n n Dynamic change of communication Anonymous communication Multi-cast and broadcast communication Cascading effects (wavefront..) If an abstraction has two aspects n And one of them depends on the other n Reuse of aspects is possbile. 47 Observer Implementation n If there is more than one subject: Send Subject as Parameter of notify(Subject s). n Push model: subject sends data in notify() n Pull model: observer fetches data itself n Mediator between subjects and observer: n May filter events n Stops cascaded propagations 48 Observer with ChangeManager 3UBJECT Subjects Observer REGISTER3UBJ ECT/BSERVER REGISTER/BSERVER /BSERVER UPDATE 3UBJ ECT UNREGISTER 3UBJECT/BSERVER UNREGISTER /BSERVER manager NOTIFY #HANGE-ANAGER NOTIFY Subject-Observer-mapping manager.notify() manager.register(this,b) 3IMPLE#HANGE-ANAGER $!'#HANGE-ANAGER register(Subject,Observer) unregister(Subject,Observer) notify() register(Subject,Observer) unregister(Subject,Observer) notify() for all s in Subjects for all b in s.Observer b.update (s) mark all observers to be updated update all marked observers 49 Bridge (Handle/Body) #LIENT Decouple an abstraction from Its implementation !BSTRACTION imp operation() )MPLEMENTATION OPERATIONS)MP imp.operationsImp() 3PEZIALIZED!BSTRACTION #ONCRETE)MPLEMENTATION! operationsImp() #ONCRETE)MPLEMENTATION" operationsImp() 50 Example Factorisation of class hierarchies with facet hierarchies 7INDOW 87INDOW 7INDOW 0-7INDOW 87INDOW 0-7INDOW )CON7INDOW 8)CON7INDOW 0-)CON7INDOW 51 Example 7INDOW 7INDOW)MP imp "RIDGE drawText() drawRectangle() DEVICEDRAW4EXT DEVICEDRAW,INIE imp.devicedrawLinie() imp.devicedrawLinie() imp.devicedrawLinie() imp.devicedrawLinie() )CON7INDOW 4RANSIENTES7INDOW 87INDOW)MP 0-7INDOW)MP drawRahmen() drawCloseButton() devicedrawText() devicedrawLinie() devicedrawText() devicedrawLine() drawRectangle() drawText() 52 drawRectangle() XDrawLine() XDrawString() Control flow Patterns n Strategy n Visitor n Iterator n Pipeline n ChainOfResponsibility 53 Strategy #LIENT contextInterface() strategy 3TRATEGIE ALGORITHM)NTERFACE #ONCRETE3TRATEGY! #ONCRETE3TRATEGY" #ONCRETE3TRATEGIE" algorithmInterface() algorithmInterface() algorithmInterface() Define a family of algoriths 54 Example Strategy Encapsulate formatting algorithms +OMPOSITION Formatter traverse() repair() &ORMATTER FORMAT Formatter.format() %INFACHER&ORMATTER 4E8&ORMATTER !RRAY&ORMATTER format() format() format() 55 Finding Patterns How to find Patterns n The process of looking for patterns to document is called PATTERN MINING. n Patterns must not be ”new”, they grasp well-known solutions! n How do you know a pattern when you come across one? The answer is you don't always know. n You may jot down the beginnings of some things you think are patterns, but it may turn out that they aren’t patterns at all, or they are only pieces of patterns n The best way to learn how to recognize and document useful patterns is by learning from others who have done it well! n Pick up several books and articles which describe patterns (don’t choose just one) and try and see if you can recognize all the necessary pattern elements. n Read as much as you can, and try to learn from the masters. 57 How to write patterns n ..is difficult! n Pattern writing involves abstraction (experience, experience, experience…) n Avoid writing ABOUT patterns; just write patterns. n Pick something you know about and then find multiple occurrences and/or descriptions. Or conversely, MINE existing software for new possible n n n n n n 58 patterns. Find out if other people have written similar patterns. Aim for quality, not quantity of patterns. Figure out why the pattern exists or applies. Pick a format for writing about it. Circulate it to others (for example, via web pages, patterns discussion groups, or submissions to a mailing list) and receive comments. Continually iterate and refine. Tooling n IDEs n Together (Object International) n Refactoring tools n Refactorings are automated semantics-preserving transformations which INTRODUCE design patterns n COMPOST/Recoder recoder.sourceforge.net n XPTools AB Linköping 59 The End 60