5. Design patterns The concept of a design pattern Benefits of design patterns Description of design patterns Antipatterns Example: Composite Design patterns and frameworks Design patterns & UML Design patterns are not... Summary http://www.enteract.com/~bradapp/docs/patterns-intro.html http://www.hillside.net/patterns/ 1
The concept of a design pattern Cristopher Alexander et al.: A Pattern Language, 1977 Cristopher Alexander: The Timeless Way of Building, 1979 World consists of repeating instances of various patterns Example: Every farmer can build a barn - why? A pattern is (possibly hidden) design knowhow that should be made explicit Well known in other engineering areas Particularly useful concept in software engineering 2
Esimerkki: Ikkunat ja ovet hirsitalossa hirret painuvat kasaan Ongelma: ikkunat ja ovet ovat kiinteitä, vaikka hirsiseinä liikkuu ja painuu kasaan. Ratkaisu: ikkunoiden ja ovien karmeja ei kiinnitetä suoraan seinään, vaan "karaan", joka liikkuu vapaasti hirsiin tehdyssä urassa. 3
What is a design pattern? Design pattern A general solution to a frequently occurring architecture/design problem in a context. 4
Explanation of the definition General solution... not specific to language, environment etc. described as a semiformal document...frequently occurring... must be a common problem...architecture/design problem... applied at architecture or detailed design level...in a context. the problem appears in a context that defines certain requirements or forces 5
Benefits of design patterns Design patterns... make hidden design knowledge explicit and available; can be used to document systems (instances of design patterns); name and make explicit a higher-level structure which is not directly supported by a programming language; can be used as architectural building blocks; give a common vocabulary for designers. 6
Description of a design pattern Essential parts: Name Problem Solution Consequences Implementation Increases design vocabulary Description of the problem and its context, presumptions, example Basic arrangement of classes and objects to solve a problem (e.g. using UML) Benefits and drawbacks of applying the design pattern Different choices in the implementation of the design pattern, possibly language-dependent 7
Description of design patterns in GoF "Gang of Four book, GoF: Gamma E., Helm R., Johnson R., Vlissides J.: Design Patterns - Elements of Reusable Object-Oriented Software. Addison-Wesley 1995. Name (and category) Intent Also known as Motivation Applicability Structure Participants Collaborations Consequences Implementation Sample code Known uses Related patterns 8
Anti-patterns Problem Pattern Pattern solution Consequences Antipattern solution Symptoms Re-engineering Antipattern Antipattern = solution + solution Pattern = problem + solution Brown W.J. et al.: Antipatterns - Refactoring Software, Architectures, and Projects in Crisis. Wiley 1998. 9
General anti-pattern characteristics Code repetition Branching on the basis of data types (classes) Possible alternatives statically fixed in code Superclass knows its subclass Unnecessary downcasting Unclear, unintuitive interfaces Large classes and operations 10
Finding patterns: a simple exercise Assume that class Shape is the general superclass of all kinds of graphical shapes like rectangles, circles etc. Each shape knows its coordinates in the two-dimensional space, and how to draw itself at those coordinates (method draw ). For each shape, the method move(x,y) (move the shape x units in x-direction and y units in y-direction) can be implemented by first redrawing the shape in white (background) color at the original position, computing the new coordinates and then drawing a new shape in black at the new coordinates. Assume that system operation setcolor(color) changes the drawing color. Give a design solution in which there is no (or minimal) code duplication for classes Shape, Square and Circle. Use UML. 11
Shape draw() move(dx,dy) setcolor(white) draw() x = x + dx y = y + dy setcolor(black) draw() Rectangle draw() draw() Circle 12
Template Method design pattern Abstract TemplateMethod() Operation1() Operation2() Operation1() Operation2()... Concrete Operation1() Operation2() 13
Example: Composite Problem: how to manage a hierarchical composition of objects? Eg., execute an operation for each leaf object in the hierarchy, without needing to know the details of the structure. Client do operation x 14
Developing the composite pattern (1) First solution: two-levels Composite forall() * children Leaf operation() if X is Composite then X.forall() else X.operation;... For all children c: c.operation() Symptoms: - Composite and leafs always treated differently in code - Difficult to extend (new kinds of leafs or composites, unrestricted depth) if X is Composite then Op1(, X, ) else Op2(, X, );... 15
Developing the composite pattern (2)( Second solution: Unified treatment in client and unrestricted depth of parts * children Item operation() íf I have children then for all children c: c.operation() else dosomething(); Client: item.operation() 16
Developing the composite pattern (3)( Third solution: New types of elements * children Item operation() íf I have children then for all children c: c.operation() else dosomething1() Item1 operation() Item2 operation() íf I have children then for all children c: c.operation() else dosomething2() 17
Developing the composite pattern (4)( Fourth solution: Separating the composite class * children Item operation() Item1 Composite dosomething operation() operation() for all children c: c.operation() 18
Name: Composite Composite design pattern Problem: How to organize hierarchical object structures so that the clients are not aware of the hierarchy? Solution: Item operation() * children Leaf operation() Composite operation() For all children c: c.operation() 19
Composite (cont.) Applicable when: you want to represent part-whole hierarchies of objects you want clients to be able to ignore the difference between composite and elementary objects Consequences: Whereever a client handles a composite object it can handle an elementary object and vice versa Client code becomes simpler Facilitates the adding of new composite and elementary types May overgeneralize: does not support a structure that allows only certain kinds of objects 20
Composite (cont.) Implementation concerns Both parent and child references needed? Can the same element belong to several composites? Common interface, type security Are the elements ordered? Who creates and destroys the elements? Which data structure is used for storing the elements? 21
Example of applying Composite SourceManager Source delete() print() * children File delete() print() Folder delete() print() add(source) For all children c: c.delete(); Delete folder 22
Exercise Figures consist of individual geometric figures (like circle, square etc.) and groups of figures. Give an architectural solution in UML, allowing figures and groups of figures to be treated (e.g. draw) in the same way so that a client need not know whether it is manipulating an individual figure or a group of figures. 23
Graphicaltem draw * children Rectangle Circle FigGroup draw draw draw for all children c: c.draw; 24
Design patterns and frameworks Graphicaltem draw * children Framework Rectangle Circle FigGroup draw draw draw Application for all children c: c.draw; 25
Pattern lifecycle Pattern mining Pattern specification Incomplete pattern instance Pattern instance Pattern catalog Framework Application Pattern implementation 26
Design patterns and UML Composite Item Statement * execute() Leaf Composite SimpleStatement execute() Block execute() children 27
Patterns in a model EventSource register(statemachine) * * informs StateMachine 1 run(state) handle(event) Singleton State Observer Event source(): Object current.exit(); current = current.transit(e); current.entry(); uses 0..1 current State transit(event): State entry() exit() Event1 source(): Object Event2 source(): Object StateA transit(event): State entry() exit() StateB transit(event): State entry() exit() 28
Another approach <<Composite:item>> Statement * execute() <<Composite:leaf>> SimpleStatement execute() <<Composite: composite>> Block execute() children 29
Design patterns are not parts of a system; general remedy to improve your system; God-given; without potential problems: design fragmentation overkilling problems excessive dynamic binding object schitzophrenia implicitness 30
Summary Design patterns present in a systematic way proven, good design solutions Design patterns are framework building blocks Use a design pattern only after recognizing the problem Design patterns concern experience, not inventions Design patterns are about common sense - use them with common sense 31