Definition T A Design Pattern is T T T Design Patterns T a description of a standard solution for a standard problem in design. Goal: Reuse of design information A pattern must not be “new”! Uwe Assmann RISE (Slides derived from Walter F. Tichy, Universität Karlsruhe, Germany, Used by permission) 3 Introduction T What is a Design Pattern? T Christopher Alexander “The timeless way of building” For what can they be used? How does it look like? T Hunting for the “Quality without a name” Patterns grasp centers of beauty You have a language for beauty, consisting of patterns T T T T Literature: T T T T T T 2 Alexander’s Laws on Beauty T „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, AddisonWesley, 1995,... „Software Architecture”, Shaw & Garlan, Prentice Hall, 1996. “Object-oriented Design and Patterns” W. Pree, 1995, AddisionWesley TDDB84 “Design Patterns” (running in period I, 2003) T T T T 4 a book of the century: A MUST dependent on culture Beauty cannot be invented but must be combined/generated by patterns from a pattern language Alexander means “composition” Example: Model/View/Controller (MVC) Model/View/Controller Relation between model and views is grasped by the design pattern Observer. T Views may register at the model (observers). T They are notified if the model changes. Then, every view updates itself by accessing the data of the model. T Views are independent of each other. The model does not know how views visualize it. T Observer decouples strongly. MVC is a agglomeration of classes to control a user interface and a data structure (from Smalltalk) T T T Model: View: Controller: Data structure or object, invisible Representation(s) on the screen Encapsulates reactions on inputs of users, couples model and views MVC is a complex design pattern and combines the simpler ones compositum, strategy, observer. 5 7 Views as Observer Window x y z a 60 50 80 b 30 30 10 Pattern 2: Compositum Window Views may be nested. (Compositum) T Example: object inspector in debuggers T Compositum requires that Window c 10 20 10 T a b T c a=50% b=30% c=20% Model 6 8 The class CompositeView is a subclass of View Can be used in the same way as View Pattern 3: Strategy Purpose Design Pattern The relation between controller and view is a Strategy pattern. T There may be different control strategies 1) T T T T Lazy or eager update of views Menu or keyboard input A view may select subclasses of Controller, even dynamically No other class changes Improve communication in teams 1) 2) 2) Abstracts design concepts 1) 2) 3) 3) 2) 3) 9 Patterns are “mini-frameworks” Documentation May be used to capture information in reverse engineering Improvement of the state of the art of software engineering 1) 4) 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 11 Structure for Design Pattern T There are several formats T T T T T Name (incl. Synonyms) Task and Context Solution T T T 10 Gof (Gamma Gang of Four) Alexandrian format Structure (Components, Relations): UML class or object diagram Interactions und Consequences: interaction diagrams Implementation (code examples) Design Pattern Catalogue Overview Patterns Design Pattern Categories T M T T T T T T T several are around Basic patterns characterize simple collaboration scenarios in class graphs, sequence diagrams, or other diagrams. T Basic 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 Data patterns Singleton: globally unique objects Flyweight: Space optimizations by representants Memento: Snapshot of state T A classification is hard T T Are used to form larger patterns T Data patterns characterize state of a set of objects and their responsibilities Creational Patterns determine how objects and object families are allocated Coupling patterns (Structural patterns) divide systems into subsystems such that these can be exchanged independently Commonality patterns condense common parts of classes into new classes Control flow patterns (Behavioral patterns) describe common control flow situations T T T T T T T 13 • • • • • • • • • Coupling Patterns 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: • Control flow (behavioral) patterns • 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 • • • • • • Creational Patterns • FactoryMethod: Vary allocation in subclass • Abstract Factory: Allocation of object family • Builder:Incremental allocation of complex structured object • Prototype: Clone an object 15 Relations between Patterns [Zimmer PLOP 1] Creation patterns Builder Prototype Coupling patterns Control flow patterns Interpreter Layers Strategy Basic Patterns T Visitor Facade Abstract Factory T Iterator ChainOf Responsibility Observer T T Bridge FactoryMethod According to [W. Zimmer: Frameworks und Design Pattern, PhD 1997 Universität Karlsruhe] Design Patterns can be build from the following basic ones: T Comman T T T T Template Method Objectifier Proxy Compositum Singleton Memento Adapter Mediator Glue Basic patterns Decorator Flyweight Data patterns 16 TemplateMethod Objectifier (Delegation) Mediator Decorator Proxy Compositum Adapter Data Patterns T Singleton (singleton) T Flyweight T Memento Template Method Objectifier (Delegation Object) T AbstractClass TemplateMethod() primitiveOperation1() primitiveOperation2() ... primitiveOperation1(); ... primitiveOperation2(); ... T T T T T ConcreteClass 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. primitiveOperation1() primitiveOperation2() Define the skeleton of an algorithm (template method) Delegate parts to hook methods that are filled by subclasses 17 19 Template Method T Allows for varying behavior. Separate invariant from variant parts of an algorithm Factor out common code into super classes T Control extensions by only allowing “hook methods” T T T 18 Avoid code replacement Mediator T T T 20 Mediators encapsulate communication Partners can register with the mediator and do not know with whom they talk Communication can be varied dynamically Mediator Example Mediator Mediator Mediator Decoupling windows from text fields Colleague Mediator DialogueMediator ConcreteMediator ConcreteColleague1 showDialog() createWidgets() widgetChanged(Widget) ConcreteColleague2 Widget changed() Mediator.widgetChanged(this) Typical Object Structure: AColleague AConcreteMediator AColleague Mediator AColleague Mediator T T T T createWidgets() widgetChanged(Widget) InputField select() field Mediator 23 Example Mediator T liste TextDialogueMediator AColleague 21 T ListBox Mediator Proxy Many dependencies between parts of a window Different widgets have different dependencies Encapsulate behavior in a mediator that mediates between widgets Spare class factorization Widgets can be registered/unregistered dynamically Flexible, but anonymous communication Subject Client operation() ... realSubject RealSubject Proxy operation() ... operation() ... ... realSubject.operation() Hide the access to a real subject by a representant 22 24 Proxy T T T T T References instead of values Protocol proxy: counts references (reference-counting garbage collection Indirection proxy: assembles all references to an object to make it replaceable Remote proxy: representant of a remote object Caching proxy: caches values which had been loaded from the subject T T T Adapter (2) Client AdaptierteClass operation() spezificOperation() adapted Object Adapter Remote Loading lazy on demand operation() adaptedObject.spezificOperation() Protection proxy T Goal Without Multiple Inheritance, but object adapter Firewall 25 27 Adapter (Wrapper) Example: Use of an External Class Library External Library Client GoalClass AdaptedClass operation() specificOperation() DrawingEditor GraficObject framew() createManipulator() Can also be interface TextDisplay largeness() (Implementation) Adapter operation() specificOperation() Adapts an interface to a client May use multiple inheritance, but need not 26 Linie Text frame() createManipulator() frame() createManipulator() return text.largeness() return new TextManipulator 28 Compositum Compositum Part/Whole hierarchies, e.g., nested graphic objects T Class Compositum contains a container for the child objects aPicture T Pattern is hard to employ when it sits on top of a complex inheritance hierarchy T aPicture aPicture aLine aLine For iterations on hierarchies aRectangle aRectangle common operations: draw(), move(), delete(), scale() 29 31 Structure Compositum Client Data Patterns Component commonOperation() add(Component) remove(Component) getType(int) Memento } Pseudo implementations childObjects 30 Leaf Compositum commonOperation() commonOperation() add(Component) remove(Component) getType(int) for all g in childObjects g.operation() 32 Flyweight Singleton Structure for Singleton Structure for Flyweight Flyweighte FlyweightFactory Singleton Flyweight getFlyweight(key) static Singleton() private Singleton (first: bool) operation() getDaten() if uniqueInstance == null then uniqueInstance = new Singleton (true) return uniqueInstance operation(extrinsicState) if (Flyweighte[key] exists){ return Flyweight[key]; } else { create new Flyweight; add to Flyweight; return it; } static uniqueInstance data Assure one globally unique object of a class ConcreteFlyweight SeparatelyUsed ConcreteFlyweight operation(extrinsicState)) operation(extrinsicState)) intrinsicState gesamtState Client 33 35 Flyweight T T T T Representants with minimal space Example Flyweight Object modeling for characters in editor Set of objects is very large State can be moved from object to external memory (extrinsic state) Identity of objects can be neglected Introduce flyweight objects Column Row e 34 36 Row x a m Row p Set of Flyweights 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 Memento Coupling (Structural) Patterns T Extensionalize state of object T Client Memento restore(Memento m) createMemento() getState() setState() State State return new Memento(State) memento T Container T Observer Bridge (Adapter) Facade State = m.getState() 37 39 Example Memento Observer (Publisher/Subscriber) Observer Breakpoints and Undo in editors, debuggers: Window x y z a 60 50 80 b 30 30 10 Window a Rectangles should stay linked If they are moved. 38 Window c 10 20 10 b c a=50% b=30% c=20% Undo might be wrong if state Is not sufficiently memorized Subject 40 Notify on change Queries Structure Observer Observer Subject register(Observer) unregister(Observer) notify() Observer T Loose coupling in communication T Dynamic change of communication Anonymous communication Multi-cast and broadcast communication Cascading effects (wavefront..) If an abstraction has two aspects Observer T update () T for all b in Observer { b.update () } T T ConcreteObserver Subject Concreteubject getState() setState() T ObserverState = Subject.getState() update () T T ObserverState Observers decide what happens And one of them depends on the other Reuse of aspects is possbile. return SubjectState SubjectState 41 43 Sequence Diagram Observer aConcreteubject aConcreteObserver anotherConcreteObserver register() Observer Implementation T T setState() T notify() T If there is more than one subject: Send Subject as Parameter of notify(Subject s). Push model: subject sends data in notify() Pull model: observer fetches data itself Mediator between subjects and observer: T T update n() getState() update n() getState() 42 44 May filter events Stops cascaded propagations Event Channel T T T T Bridge (Handle/Body) Anonymous communication with events Partners don’t know each other Combination of Mediator and Observer Also called software bus Client Decouple an abstraction from Its implementation Abstraction imp Implementation operation() operationsImp() imp.operationsImp() ConcreteImplementationA SpezializedAbstraction operationsImp() ConcreteImplementationB operationsImp() 45 47 Structure Event Channel T Example An event channel is a mediator that communicates with events, and let every partner register as subject and observer Factorisation of class hierarchies with facet hierarchies Window Window Event channel (software bus) XWindow Send Event Register Unregister Partner 1 46 PMWindow XWindow PMWindow IconWindow receiveEvent partner N XIconWindow 48 PMIconWindow Example Facade imp Window drawText() drawRectangle() WindowImp Clients devicedrawText() devicedrawLinie() Bridge imp.devicedrawLinie() imp.devicedrawLinie() imp.devicedrawLinie() imp.devicedrawLinie() Facade IconWindow TransientWindow XWindowImp PMWindowImp drawRahmen() drawCloseButton() devicedrawText() devicedrawLinie() devicedrawText() devicedrawLine() Subsystem drawRectangle() drawText() drawRectangle() XDrawLine() XDrawString() 49 51 Facade T Encapsulate a set of classes into a subsystem, and represent this subsystem by a façade class Possible on object level T Better information hiding T T Then at run time façade objects exist Facade T Façade provides a view to the subsystem T Facades decouple, minimize dependencies Allow to exchange and reuse subsystem easier If classes of the subsystem are again facades, layers result T T T T T 50 52 There may be several views, several facades The reliesOn relation is acyclic Layers are nested facades (reducible graphs!) Façade and Layers Control Flow Patterns T Strategy Command Visitor T ChainOfResponsibility T Clients T T Iterator Upper layer Facade Lower layer 53 55 Façade and Layers T T Have been used no several times Acyclic uses/reliesOn relation T T Strategy Nested facades enforce an acyclic uses relation! Client Layered design with abstract machines contextInterface() strategy Strategy algorithmInterface() ConcreteStrategyA ConcreteStrategyB ConcreteStrategyB algorithmInterface() algorithmInterface() algorithmInterface() Define a family of algoriths 54 56 Example Strategy Structure for Command Encapsulate formatting algorithms Caller Client Composition Formatter traverse() repair() Command exec() Formatter format() Receiver Formatter.format() Receiver action() SimpleFormatter TeXFormatter ArrayFormatter format() format() format() ConcreteCommand exec() State Receiver.action() 57 59 Command (Command Object) T T Represent (reify) a command as an object Object T T T T T T T Example for Command Can be undone Can be memoized Waiting queues Multi-user management Parameterization of commands Protocol of commands Application Menu MenuEntry Command add (Document) add(MenuEntry) clicked() exec() Command.exec() Dokument open() close() cut() copy() paste() Also know as Action, Transaction document PasteCommand exec() document.paste() A command has a method exec which executes the operation 58 60 Command for Opening Document Visitor T Command T exec() T T application Application add (Document) OpenCommand exec() queryUser() Document open() close() cut() copy() paste() T Encapsulate an operation on a collection (tree) of objects as an object. Separate tree inheritance hierarchy from command hierarchy Simple extensibility of both hierarchies Simpler inheritance structures, otherwise multiplication of classes Abbreviation for multi methods T T name = queryUserr() dok = new Documnt(name) application.add(dok) dok.open() 61 dispatch/polymorphism on two arguments, not only the first First dispatch on tree object (method accept), then operation (method visit) objects 63 MacroCommand With Compositum Structure for Visitor Client Visitor visitConcreteElemA(ConcreteElementA) visitConcreteElemB(ConcreteElementB) Command exec() MakroCommand ConcreteVisitor1 ConcreteVisitor2 visitConcreteElemA(ConcreteElementA) visitConcreteElemB(ConcreteElementB) visitConcreteElemA(ConcreteElementA) visitConcreteElemB(ConcreteElementB) Commande ObjectStructure exec() Element accept(Visitor) ConcreteElementA for all b in Commande b.exec() ConcreteElementB accept(Visitor b) operationA() accept(Visitor) operationB() b.visitConcreteElementA (this) 62 64 b.visit...B (this) Example Compiler Abstract Syntax Trees Relations between Patterns [Zimmer PLOP 1] Creation patterns Builder Prototype Coupling patterns Control flow patterns Interpreter Layers Strategy Visitor Node Facade typeCheck() generateCode() prettyPrint() The operations are distributed Over the classes. In case of extensions, All classes must be extended. VariableRefNode AssignmentNode typeCheck() generateCode() prettyPrint() typeCheck() generateCode() prettyPrint() Abstract Factory Iterator ChainOf Responsibility Observer Bridge FactoryMethod Command Template Method Objectifier Proxy Compositum Singleton Memento Adapter Mediator 65 Basic patterns Abstract Syntax Trees with Visitors The End NodeVisitor visitAssignment(AssignmentNode) visitVariableRef(VariableRefNode) TypeCheckingVisitor CodeGenerationVisitor visitAssignment(AssignmentNode) visitVariableRef(VariableRefNode) visitAssignment(AssignmentNode) visitVariableRef(VariableRefNode) Program Node accept(NodeVisitor) AssignmentNode VariableRefNode accept(NodeVisitor b) accept(NodeVisitor) b.visitAssignment (this) 66 Glue b.visitVariableRef (this) 68 Decorator Flyweight Data patterns