Docsity

Design Patterns - Programming Language Technologies and Paradigms | CMSC 433, Study notes of Programming Languages

Toggle sidebar
bg1
117
CMSC 433 – Programming Language
Technologies and Paradigms
Spring 2004
Design Patterns
February 26, 2004
118
Lexi: Using Strategy
•Compositor and Composition classes
– Compositor: class encapsulating formatting algorithm
•Pass Composition objects to be formatted as parameters to
Compositor methods
–Composition: things being formatted
•Glyph subclass
•Each Composition object refers to its Compositor object
•When a Composition needs to format itself, it sends a message to its
Compositor instance
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17

Partial preview of the text

Download Design Patterns - Programming Language Technologies and Paradigms | CMSC 433 and more Study notes Programming Languages in PDF only on Docsity!

117

CMSC 433 – Programming Language

Technologies and Paradigms

Spring 2004

Design Patterns February 26, 2004

Lexi: Using Strategy

  • Compositor and Composition classes
    • Compositor: class encapsulating formatting algorithm
      • Pass Composition objects to be formatted as parameters to Compositor methods
    • Composition: things being formatted
      • Glyph subclass
      • Each Composition object refers to its Compositor object
      • When a Composition needs to format itself, it sends a message to its Compositor instance

119

Class Diagram

Object Structure after Formatting

123

Visitor: Implementing Analyses

  • Often want to implement multiple analyses on the same kind of object data - Spellchecking and Hyphenating Glyphs - Generating code for and analyzing an Abstract Syntax Tree (AST) in a compiler
  • One solution: implement each analysis as a method in each object - Follows idea “objects are responsible for themselves” - But many analyses will occlude the object’s main code - Result is classes hard to maintain

Abstract Syntax Trees

public interface Node { } public class Number extends Node { public int n; } public class Plus extends Node{ public Node left; public Node right; }

125

Traversing Abstract Syntax Trees

public interface Node { public int sum(); } public class Number extends Node { public int n; public int sum() { return n; } } public class Plus { public Node left; public Node right; public int sum() { return left.sum() + right.sum(); } }

Naïve approach (not a visitor)

One method for each analysis

129

How to perform traversal?

  • Now that we have a visitor class, how do we apply its analysis to the objects of interest? - Add accept(visitor) method to each structure class, that will invoke the given visitor on this. - Builds on Java’s dynamic dispatch. - Use an iteration algorithm (like an Iterator) to call accept() on each relevant object.

Sample visited objects

131

Vistor Interaction

aNodeStructure aAssignmentNode^ aVariableRefNode^ aTypeCheckingVisitor Accept (aTypeChecking Visitor) VisitAssignment(aAssignmentNode) VisitVariableRef (aVariableRefNode) Accept (aTypeCheckingVisitor) someOperation() someOperation()

Visitor pattern

  • Name
    • Visitor or double dispatching
  • Applicability
    • Related objects must support different operations and actual op depends on both the class and the op type
    • Distinct and unrelated operations pollute class defs
    • Key: object structure rarely changes, but ops changed often

135

Use of Visitor Pattern in Lexi

Visitor Pattern Consequences

  • Adding new operations is easy
    • Add new op subclass with method for each concrete elt class
    • Easier than modifying every element class
  • Gathers related operations and separates unrelated ones
  • Adding new concrete elements is difficult
    • Must add a new method to each concrete Visitor subclass
  • Allows visiting across class hierachies
    • Iterator needs a common superclass (i.e., composite pattern)
  • Visitor can accumulate state rather than pass it as parameters

137

Implementing Traversal

  • Who is responsible for traversing object structure?
  • Plausible answers:
    • Visitor
      • But, must replicate traversal code in each concrete visitor
    • Object structure
      • Define operation that performs traversal while applying visitor object to each component
    • Iterator
      • Iterator sends message to visitor with current element as arg

Double-Dispatch

  • Accept code is always trivial
    • Just dynamic dispatch on argument, with runtime type of structure node taking into account in method name
  • A way of doing double-dispatch
    • Traversal routine takes two arguments, the visitor and the object to traverse - o.accept(aVisitor) will dispatch on the actual identity of o (the object being considered) - ...and accept will internally dispatch on the identity of aVisitor (the object visiting it).

141

State in a Visitor Pattern

  • A visitor can contain state
    • E.g., the results of typechecking the program so far class TypeCheckingVisitor extends Visitor { private TypeMap map; void visit(VariableRefNode n) { … map.add(n,t) … } }
  • Or visitors pass around a separate state object
    • Impacts the type of the Visitor superclass

Traversals

  • It’s sometimes preferabke to try to keep traversal separate from the Visitor - E.g., use an Iterator - Thus traversal and analysis can evolve independently
  • But can also do it within node or visitor class. Several solutions here: - acceptAndTraverse methods - traverse from within accept() - Separating processing from traversal - Visit/process methods - Traversal visitors applying an operational visitor

143

acceptAndTraverse Methods

  • Accept method could be responsible for traversing children - Assumes all visitors have same traversal pattern - E.g., visit all nodes in pre-order traversal - Could provide previsit and postvisit methods to allow for more complicated traversal patterns - Still visit every node - Can’t do out of order traversal - In-order traversal requires inVisit method

Accept and Traverse

  • Class BinaryPlusOperatorNode { void accept(Visitor v) { v.visit(this); lhs.accept(v); rhs.accept(v); } …}

147

Visit/Process, Continued

  • Can define a PreorderVisitor
    • Extend it, and just redefine process method
      • Except for the few cases where something other than preorder traversal is required
  • Can define other traversal visitors as well
    • E.g., PostOrderVisitor

Traversal Visitors Applying an

Operational Visitor

  • Define a Preorder traversal visitor
    • Takes an operational visitor as an argument when created
  • Perform preorder traversal of structure
    • At each node
      • Have node accept operational visitor
      • Have each child accept traversal visitor

149

PreorderVisitor with Payload

  • Class PreorderVisitor { Visitor payload; void visit(BinaryPlusOperatorNode n) { payload.visit(n); n.lhs.accept(this); n.rhs.accept(this); } …}

Back to Lexi

153

Monoglyph class: a Decorator

Class Monoglyph { … void Draw (Window w) { component.Draw(w); } … } Class Border extends Monoglyph { .. void Draw (Window w) { super.Draw(w); DrawBorder(w); } … }

Changing Look-and-Feel: Abstract Factory

  • Goal: easily change Lexi’s look-and-feel
    • When new libraries are available (future variability)
    • At run-time by switching between them (present variability)
  • Thoughtless implementation technique:
    • Use distinct class for each widget and standard
    • Let clients handle different instances for each standard
      • Button pb = new MotifButton(); // bad

155

Abstracting Creation

  • Concrete Creation problems:
    • Class of object is fixed at compile-time
      • Can’t change standard at run-time
    • Changing the class means making changes all over the code
  • Instead:
    • Use a class to create abstract classes:
      • Button pb = guiFactory.createButton();// better

Solution: Use Abstract Factory

  • Define abstract class GUIFactory with creation methods for widgets - Concrete subclasses of GUIFactory actually define creation methods for each look-and-feel standard - MotifFactory, MacFactory, etc. - Specialize each widget into subclasses for each look- and-feel standard
  • Thus, can easily change the kind of factory without changes all over the place