1 / 39

Chapter 16. Applying Patterns to Design a State Diagram Editor (Part 1)

Chapter 16. Applying Patterns to Design a State Diagram Editor (Part 1). Key Takeaway Points. Applying situation-specific patterns during the design process. Begin with the design problems encountered, select the right patterns, and apply them correctly.

mdedmon
Download Presentation

Chapter 16. Applying Patterns to Design a State Diagram Editor (Part 1)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 16. Applying Patterns to Design a State Diagram Editor(Part 1)

  2. Key Takeaway Points • Applying situation-specific patterns during the design process. Begin with the design problems encountered, select the right patterns, and apply them correctly. • The pattern specifications are useful for verifying and validating designs that apply patterns, that is, ensuring that the right patterns are applied and applied correctly.

  3. Applying Patterns in the Methodology Context Use case-iteration allocation matrix Business goals & needs Current situation Accommodating Requirements Change Customer feedback Acquiring Requirements (Domain Modeling) Iteration use cases Domain Modeling Preliminary requirements Domain model Domain model Deriving Use Cases from Requirements Actor-System Interaction Modeling Abstract & high level use cases, use case diagrams Expanded use cases & UI design Behavior Modeling & Responsibility Assignment Allocating Use Cases & Subsystems to Iterations Behavior models Use case-iteration allocation matrix Deriving Design Class Diagram Producing an Architecture Design Design class diagram Software architecture Test Driven Development, Integration, & Deployment (b) Iterative Phase – activities during each iteration (a) Planning Phase control flow data flow control flow & data flow

  4. Situation Specific Patterns Creational patterns deal with creation of complex, or special purpose objects. Structural patterns provide solutionsfor composing or constructing large, complex structures that exhibit desired properties. Behavioral patterns are concerned with algorithm aspect of a design assignment of responsibilities to objects communication between objects

  5. Situation Specific Patterns Creational Patterns Abstract factory Builder Factory method Prototype Singleton Structural Patterns Adapter Bridge Composite Decorator Facade Flyweight Proxy Behavioral Patterns • Chain of responsibility • Command • Interpreter • Iterator • Mediator • Memento • Observer • State • Strategy • Template method • Visitor

  6. Process for Applying Patterns

  7. Pattern Application Process • Perform design as usual. • Perform design activities as described in Chapters 9 through 15. Continue with Step 2 if a design problem is encountered. • Search for patterns to solve design problem. • Look up patterns in Figure 16.2 of textbook. • Apply selected patterns. • Match pattern classes with design classes, introduce remaining pattern classes into existing design • Review to ensure correctness.

  8. Case Study: Design a State Diagram Editor

  9. Representing Recursive Whole-Part Structures • A state diagram consists of states and transitions, a state may be a composite concurrent state or a composite sequential state, which is a state diagram. • Design problem: how does one represent complex, recursive whole-part structures? • Class exercise: Look up a pattern from Figure 16.2.

  10. It provides default implementation for the composite-only operations. It overrides the component operations for each child child.operation(); Composite Pattern Component add(c: Component) remove(c: Component) get (...): Component operation() Client * child Composite Component add(c: Component) remove(c: Component) get (...): Component operation() Primitive Component 2 operation() Primitive Component 1 operation()

  11. Diagram Element name: String loc: Point draw(g: Graphics) intersect(p: Point): boolean add(e:DiagramElement) get (...): DiagramElement remove (e: DiagramElement) ... Edit State Diagram Controller g.drawString(name, ...); for each c in components c.draw(g); * components source Transition dest: Point draw(g: Graphics) intersect(p: Point): boolean State width: int height: int draw(g: Graphics) intersect(p: Point): boolean State Diagram path: String draw(g: Graphics) intersect(p: Point): boolean add(e:DiagramElement) get (...): DiagramElement remove(e: DiagramElement) ... * * destination draw transition draw state Applying Composite Pattern

  12. Composite Pattern The composite pattern describes recursive, part-whole relationships. It can be used to represent complex class structures. It lets the client treat the primitive components and composite components uniformly.

  13. Composite Pattern Benefits It makes the client simple the client can treat composite objects and primitive objects uniformly. the client does not know if it is dealing with a composite or primitive object. It is easy to add new kinds of composite or primitive component. Liabilities The client needs to ensure that integrity constraints are satisfied.

  14. Class Exercise In an agent-oriented system, agents dynamically generate and execute plans to accomplish their goals. A plan consists of conditional actions and sub-plans (reusability). sketch a design for representing plans what are the classes and attributes of each class? what operations each class should have? what are the appropriate semantics of the operations?

  15. Providing Layout Choices • The state diagram editor should beatify a state diagram. • There are different layout algorithms; they differ in various aspects. • Design problem: how can the editor let the user choose a layout algorithm? • Class exercise: look up Figure 16.2 to select a pattern that solve this design problem.

  16. strategy Client Strategy operation() setContext(c: Context) Contex getContextData(): Data context Strategy 3 operation () Strategy 1 operation() Strategy 2 operation () Strategy

  17. Object Interaction in Strategy client: c:Context s:Strategy K K=1, 2, 3 create() process context, may get data from context setContext(c) operation() d:=getContext():Data

  18. The client calls setLayoutAlgo(a) to set selected algorithm, then calls draw (g). layoutAlgo.layout(); for each c in components c.draw(g); layoutAlgo=a; layoutAlgo. setDiagram(self); Applying Strategy Edit Diagram Controller State Diagram draw(g: Graphics) setLayoutAlgo(a: LayoutAlgo) // other operations diagram layoutAlgo <<Strategy>> Layout Algorithm layout() setDiagram(d: State Diagram) <<Strategy>> Hierarchical Layout layout() <<Strategy>> Force-Based Layout layout() <<Strategy>> Orthogonal Layout layout()

  19. strategy Strategy operation() setContext(c: Context) Contex getContextData(): Data context Strategy 3 operation () Strategy 1 operation() Strategy 2 operation () Edit Diagram Controller <<Strategy>> Layout Algorithm layout() setDiagram(d: State Diagram) State Diagram draw(g: Graphics) setLayoutAlgo(a: LayoutAlgo) // other operations <<Strategy>> Hierarchical Layout layout() <<Strategy>> Force-Based Layout layout() <<Strategy>> Orthogonal Layout layout() Applying Strategy: The Mapping Pattern: Client Editor design:

  20. :Edit Diagram Controller :State Diagram a :Layout Algorithm beautify() setLayoutAlgo(a) setDiagram(self) draw(g) layout() for each c in components c.draw(g); Object Interaction in Editor Strategy

  21. Benefits and Liabilities of Strategy • Benefits • Eliminate conditional statements – reducing complexity. • Let the client select the algorithm – changing the behavior of the subject dynamically. • Allow different algorithms to apply to the same data structure – hiding the data structure from the subject. • Liabilities • The client must know the strategies and how to choose them. • Breaking encapsulation – the strategies may need to know the data structure of the subject. • A little increase in communication overhead.

  22. Class Exercise • Consider how strategy can be applied in the following situations: • networks routing • circuit layout • work scheduling • work flow management • discount policy • printing a document • What are the similarities and differences between • Strategy and visitor? • Strategy and bridge? • Strategy and command?

  23. Traversing Different Class Structures • A state diagram is a complex directed graph. • The digraph may be stored using different class structures. • Analyzing a state diagram needs to process each component of the diagram. • Design problem: how to process the components independent of the class structure used to store the state diagram? • Class exercise: look up a pattern for solving this design problem.

  24. It defines a common interface for all concrete iterators. Client uses concrete iterators to access concrete aggregates. return new Iterator2(self); Iterator Iterator hasNext(): boolean next(): Object remove() Aggregate iterator(): Iterator // other operations Client Iterator 2 hasNext(): boolean next(): Object remove() Iterator 1 hasNext(): boolean next(): Object remove() Aggregate 1 iterator(): Iterator // other operations Aggregate 2 iterator(): Iterator // other operations traverse traverse

  25. Analyzing Complex Structures • A state diagram consists of states and transitions. Different algorithms may be needed to process them. • Example: check description is different for a state and a transition. • If conditional statements are use to select algorithms, then the complexity will be high if there are many types of objects. • Design problem: How does one apply type-dependent operations without increasing complexity? • Class exercise: Look up patterns that can solve this design problem.

  26. Brake Body Engine Transmission Fuel Injector Fuel Filter Combustor Example: Checking Components of a Car Engineer Computer Engineer Electronic Engineer Mechanics When analyze a car, a specific engineer will visit each component of the car and check each component according to his specialty.

  27. Applying Visitor Pattern Client code: Engineer e=new ...; Iterator it=comp.iterator(); while (it.hasNext()) { CarComp c=(CarComp)it.next(); c.accept(e); } Car * comp check me Engineer CarComp get info check(e:Engine) check(b:Brake) accept(e: Engineer) Brake Engine ComputerEng. Mechanics accept(e: Engineer) //other op accept(e: Engineer) //other op check(e:Engine) check(b:Brake) check(e:Engine) check(b:Brake) e.check(self) e.check(self)

  28. analyze x Object Interaction in the Visitor Pattern <<visitor>> e:Mechanics c:CarComp client: i:Iterator :CarComp create() create() i:=iterator() c:=next() i.hasNext() accept(e) check(self) x:=getX() get information about the car component

  29. Using visitor: CarComp accept(Visitor) CarComp v.visit(self) v.visit(self) checkPCB() checkMech() Brake Engine accept (v:visitor) accept (v:visitor) Brake Engine Visitor v=new ...; CarComp c=new ...; ... c.accept(v); checkPCB() checkMech() checkPCB() checkMech() Visitor check(e:Engine) check(b:Brake) two receivers ME Visitor CE Visitor check(e:Engine) check(b:Brake) check(e:Engine) check(b:Brake) request request receiver CE: Computer Engineering ME: Mechanical Engineering Single-Dispatch and Double-Dispatch Without using visitor: CarComp c=new ...; c.checkPCB(); c.checkMech(); Double dispatch Single dispatch

  30. Collection Client Understanding Visitor Pattern components Visitor CarComp visit * check(e:Engine) check(b:Brake) accept(Visitor) Brake Engine Mechanics ComputerEng accept (v:visitor) accept (v:visitor) check(e:Engine) check(b:Brake) check(e:Engine) check(b:Brake) v.visit(self) v.visit(self) // Client code: Visitor v=new ...; Iterator it=components.iterator(); while (it.hasNext()) { CarComp c=(CarComp)it.next(); c.accept(v); }

  31. How to Apply Visitor Pattern • Design problem: • a class structure S containing classes C1, C2, ..., Cn • a set of functions f1, f2, ..., fm, applicable to classes of structure S • Without using the visitor pattern, the classes, or the iterator must implement f1, f2, ..., fm. This results in • assigning too many responsibilities to the classes • low cohesion, because f1, f2, ..., fm are not related • difficult to add analysis functions fm+1, fm+2, ... • the iterator cannot be reused for other analysis functions

  32. How to Apply Visitor Pattern • Define a visitor hierarchy consisting of • One Visitor interface with visit(C1), visit(C2), ..., visit (Cn) functions. That is, it defines a visit (Ci) function for each class Ci in the structure S. • Implement m concrete Visitor classes V1, V2, ..., Vm, corresponding to the m functions • Each concrete Visitor class Vj, j=1, 2, ..., m, implements visit (C1), visit (C2), ..., visit (Cn) to accomplish the functionality of fj. • Add an accept (v: Visitor) { v.visit (this); } method to the root class, or to each class of S.

  33. Visitor 2 Visitor 1 Visitor visit(C1) visit(C2) visit(C3) visit(C1) visit(C2) visit(C3) visit(C1) visit(C2) visit(C3) Using visitor v.visit(self) applies f1() to C1, C2, C3 C3 C2 C1 C0 visit 1+ accept(v:visitor) applies f2() to C1, C2, C3 How to Apply Visitor Pattern Each class is assigned too many responsibilities. The functions are not related – low cohesion. Difficult to introduce new functions. Without using visitor C0 f1() f 2() C1 C3 C2 f1() f2() f1() f2() f1() f2()

  34. The Visitor Pattern • Benefits • higher cohesion • without using Visitor, unrelated responsibilities are assigned to each class of the class structure • on the contrary, the visit(c: Ci) methods of each concrete visitor implement one functionality • support expert pattern • each concrete visitor class may store information that is needed to fulfill the functionality • the concrete visitor classes collaborate with objects of the structure to fulfill the responsibility

  35. The Visitor Pattern • Benefits • Support separation of concerns • the Visitor pattern separates the concerns into the concrete visitors, which can be used by different applications • Easy to add analysis functions • simply add concrete visitor classes • Visitors can accumulate state as they visit each object of the class structure • A visitor can be a singleton if it does not contain instance or share variables.

  36. The Visitor Pattern • Liabilities • Adding a new class Cj to the class structure is difficult • Need to add and implement visit(c:Cj) in each visitor class • May be cured by providing a default implementation in the abstract visitor root class • Breaking encapsulation of the class structure • A concrete visitor may need to access to the internal states of the objects visited.

  37. Store and Restore State of an Object • In Java, one can use cloning to store and restore an object. • In C++, one can use the copy constructor. • Sometimes, it is desired that only the object itself is allowed to access the stored state. • The memento pattern solves this problem.

  38. int h=pass.hashCode(); if (hash==h) return state; else throws IllegalAccessException(...); Memento m=new Memento(); State s= (State)state.clone(); m.setState(s, pass); return m; Client state=s; hash=pass.hashCode(); try { state=m.getState (pass); } catch (...) {...} State memento=subject.createMemento(); ... subject.setMemento(memento); Memento Pattern state state Subject pass: String createMemento(): Memento setMemento(m: Memento) // other operations Memento hash: int getState(pass: String): State setState(s: State, pass: String) memento subject

  39. Applying Agile Principles • Responding to change. • The team must be empowered to make decisions. • Values working software over comprehensive documentation. • Good enough is enough.

More Related