Design Patterns Dr. Uwe Assmann PELAB (Slides derived from Walter F. Tichy, Universität Karlsruhe, Germany, Used by permission) 2 Introduction What is a Design Pattern? For what can they be used? How does it look like? Literature: „Design Patterns”, Gamma et al, Addison Wesley,1995 „A System of Patterns”, Buschmann et al, Wiley, 1995. Part II from 2000 „Pattern Languages of Program Design”, Conferences, Addison- Wesley, 1995,... „Software Architecture”, Shaw & Garlan, Prentice Hall, 1996. “Object-oriented Design and Patterns” W. Pree, 1995, Addision- Wesley Special PhD Course Design Patterns (running now)
30
Embed
Design Patterns - A2Z Dotnet · Design Patterns Dr. Uwe Assmann PELAB (Slides derived from Walter F. Tichy, Universität Karlsruhe, Germany, Used by permission) 2 Introduction n What
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Design Patterns
Dr. Uwe AssmannPELAB
(Slides derived from Walter F. Tichy, UniversitätKarlsruhe, Germany, Used by permission)
2
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,1995n „A System of Patterns”, Buschmann et al, Wiley, 1995. Part II
from 2000n „Pattern Languages of Program Design”, Conferences, Addison-
Wesley, 1995,...n „Software Architecture”, Shaw & Garlan, Prentice Hall, 1996.n “Object-oriented Design and Patterns” W. Pree, 1995, Addision-
Wesleyn Special PhD Course Design Patterns (running now)
3
Definition
n A Design Pattern is a description of a standard solutionfor a standard problem in design.
n Goal: Reuse of design informationn A pattern must not be “new”!
4
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 beautyn You have a language for beauty, consisting of patterns
n dependent on culture
n Beauty cannot be invented but must becombined/generated by patterns from a patternlanguage
n Alexander means “composition”
5
Example: Model/View/Controller (MVC)
n -ODEL: Data structure or object, invisiblen 6IEW: Representation(s) on the screenn #ONTROLLER: Encapsulates reactions on inputs of
users, couples model and views
MVC is a agglomeration of classes to control a user interfaceand a data structure (from Smalltalk)
MVC is a complex design pattern and combines the simplerones compositum, strategy, observer.
6
Views as Observer
a=50%b=30%c=20%
7INDOW
a 30 30
10 20 10
b c
10
60 50 80
x y z
7INDOW7INDOW
a b c
Model
7
Model/View/Controller
Relation between model and views is grasped by thedesign 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.
8
Pattern 2: Compositum
6IEWS�may be NESTED��(#OMPOSITUM)n Example: object inspector in debuggersn Compositum requires that
n The class CompositeView is a subclass of Viewn Can be used in the same way as View
9
Pattern 3: Strategy
The relation between CONTROLLER�and VIEW is a 3TRATEGYpattern�
n There may be different control strategiesn Lazy or eager update of viewsn Menu or keyboard input
n A view may select subclasses of #ONTROLLER��evendynamically
n No other class changes
10
Structure for Design Pattern
n There are several formatsn Gof (Gamma Gang of Four)n Alexandrian format
n Name (incl. Synonyms)n Task and Contextn Solution
n Structure (Components, Relations): UML class or object diagramn Interactions und Consequences: interaction diagramsn Implementation (code examples)
11
The GoF Template
0ATTERN�.AME��3COPE��0URPOSE
The pattern’s name conveys the essence of the pattern succinctly. A good name isvital, 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 particulardesign 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 objectstructures in the pattern solve the problem. The scenario will help youunderstand the more abstract description of the pattern that follows.
12
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 yourecognize 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.
13
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?
14
A Pattern...
n Describes a single kind of problem.n Describes the context in which the problem occurs.n Describes the solution as a constructable software entity.n Describes design steps or rules for constructing the solution.n Describes the forces leading to the solution.n Describes evidence that the solution optimally resolves forces.n Describes details that are allowed to vary, and those that are not.n Describes at least one actual instance of use.n Describes evidence of generality across different instances.n Describes or refers to variants and subpatterns.n Describes or refers to other patterns that it relies upon.n Describes or refers to other patterns that rely upon this pattern.n Relates to other patterns with similar contexts, problems, or
solutions.
15
Purpose Design Pattern
• Improve communication in teams• Between clients and programmers• Between designers, implementers and testers
• 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 softwareengineering• 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
16
Design Pattern Categories
n A classification is hardù several are around
n "ASIC�PATTERNS characterize simple collaboration scenarios in classgraphs, sequence diagrams, or other diagrams.n Are used to form larger patterns
n $ATA�PATTERNS characterize state of a set of objects and theirresponsibilities
n #REATIONAL�0ATTERNS determine how objects and object families areallocated
n #OUPLING�PATTERNS �3TRUCTURAL�PATTERNS divide systems intosubsystems such that these can be exchanged independently
n #OMMONALITY�PATTERNS condense common parts of classes intonew classes
n #ONTROL�FLOW�PATTERNS��"EHAVIORAL�PATTERNS describe commoncontrol flow situations
Define the skeleton of an algorithm (template method)Delegate parts to HOOK�METHODS that are filled by subclassesAllows to vary behavior.
22
Template Method
n Separate invariant from variant parts of an algorithmn Factor out common code into superclasses
n Avoid code replacement
n Control extensions by only allowing “hook methods”
23
Objectifier (Delegation Object)
n Reify a method by an objectn Delegate the behavior of the method to the objectn Vary the delegateen Factorizationn Varying behaviorn Used with: Bridge, Builder, Command, Iterator, Observer,
State, Strategy, Visitor.
24
Mediator
n Mediators encapsulate communicationn Partners can register with the mediator and do not know
with whom they talkn Communication can be varied dynamically
n Loose coupling in communicationn Observers decide what happens
n Dynamic change of communicationn Anonymous communicationn Multi-cast and broadcast communicationn Cascading effects (wavefront..)n If an abstraction has two aspects
n And one of them depends on the othern Reuse of aspects is possbile.
48
Observer Implementation
n If there is more than one subject: Send Subject asParameter of notify(Subject s).
n Push model: subject sends data in notify()n Pull model: observer fetches data itselfn Mediator between subjects and observer:
n May filter eventsn Stops cascaded propagations
49
Observer with ChangeManager
3UBJECT
REGISTER�/BSERVER
UNREGISTER�/BSERVER
NOTIFY�
/BSERVERObserver
#HANGE-ANAGER
REGISTER�3UBJECT�/BSERVER
UNREGISTER�3UBJECT�/BSERVER
NOTIFY�
Subject-Observer-mapping
UPDATE��3UBJECT
for all s in Subjects for all b in s.Observer b.update (s)
mark all observers to be updatedupdate all marked observers
n The process of looking for patterns to document is called PATTERNMINING.
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 piecesof patterns
n The best way to learn how to recognize and document useful patterns isby learning from others who have done it well!
n Pick up several books and articles which describe patterns (don’tchoose just one) and try and see if you can recognize all the necessarypattern elements.
n Read as much as you can, and try to learn from the masters.
58
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/ordescriptions. Or conversely, MINE existing software for new possiblepatterns.
n Find out if other people have written similar patterns.
n Aim for quality, not quantity of patterns.
n Figure out why the pattern exists or applies.
n Pick a format for writing about it.
n Circulate it to others (for example, via web pages, patterns discussiongroups, or submissions to a mailing list) and receive comments.
n Continually iterate and refine.
59
Tooling
n IDEsn Together (Object International)
n Refactoring toolsn Refactorings are automated semantics-preserving
transformations which INTRODUCE�design patternsn COMPOST/Recoder recoder.sourceforge.netn XPTools AB Linköping