Docsity

Design Patterns: Understanding the Bridge and Visitor Patterns, Papers of Programming Languages

Toggle sidebar
bg1
122
CMSC 433 – Programming Language
Technologies and Paradigms
Spring 2005
Design Patterns
February 24, 2005
123
Spell-Checking and Hyphenation
• Must do textual analysis
– Multiple operations and implementations
• Must add new functions and operations easily
• Must efficiently handle scattered information and
varied implementations
– Different traversal strategies for stored information
• Should separate actions from traversal
124
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
125
Abstract Syntax Trees
public interface Node { }
public class Number ext ends Node {
public int n;
}
public class Plus exten ds Node{
public Node left;
public Node right;
}
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Design Patterns: Understanding the Bridge and Visitor Patterns and more Papers Programming Languages in PDF only on Docsity!

122

CMSC 433 – Programming Language

Technologies and Paradigms

Spring 2005

Design Patterns

February 24, 2005

123

Spell-Checking and Hyphenation

  • Must do textual analysis
    • Multiple operations and implementations
  • Must add new functions and operations easily
  • Must efficiently handle scattered information and

varied implementations

  • Different traversal strategies for stored information
  • Should separate actions from traversal

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; }

126

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(); } } 127

Naïve approach (not a visitor)

One method for each analysis

Use a Visitor

  • Alternatively, can define a separate visitor class
    • A visitor encapsulates the operations to be performed on an entire structure, e.g., all elements of a parse tree
  • Allows operations to be separate from structure
    • But doesn’t necessarily require putting all of the structure traversal code into each visitor/operation

Sample Visitor class

134

Visitor Pattern Structure

  • Define two class hierarchies
    • One for object structure
      • AST in compiler, Glyphs in Lexi
    • One for each operation family, called visitors
      • One for typechecking, code generation, pretty printing in compiler
      • One for spellchecking or hyphenation in Lexi 135

Structure of Visitor Pattern

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

138

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 139

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).

Using Overloading in a Visitor

  • You can name all of the visitXXX(XXX x)

methods just visit(XXX x)

  • Calls to Visit (AssignmentNode n) and Visit(VariableRefNode n) distinguished by compile-time overload resolution

Visitors Can Forward Common Behavior

  • Useful for composites
    • If subclasses of a particular object all treated the same
    • Can have visit(SubClass) call visit(SuperClass)
  • For example
    • visit(BinaryPlusOperatorNode) can just forward call to superclass visit(BinaryOperatorNode)

146

Visitor/Process Methods

  • Can have two parallel sets of methods in visitors
    • Visit() methods
    • Process() methods
  • Allows finer-grained subtyping of Visitor classes

that include traversal

  • Subclass a visitor, and just change the process method
  • How it works: the visit() method on a node:
  • Calls process() method of visitor, passing node as an argument
  • Calls accept() on all children of the node (passing the visitor as an argument) (^147)

Preorder Visitor

  • Class PreorderVisitor {

void visit(BinaryPlusOperatorNode n) {

process(n);

n.lhs.accept(this);

n.rhs.accept(this);

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

150

PreorderVisitor with Payload

  • Class PreorderVisitor {

Visitor payload;

void visit(BinaryPlusOperatorNode n) {

payload.visit(n);

n.lhs.accept(this);

n.rhs.accept(this);

151

Back to Lexi

Adding Scroll Bars and Borders: Decorator

  • How to define classes for scrollbars and borders?
  • Define as subclasses of Glyph
    • Scrollbars and borders are displayable objects
    • Will use notion of transparent enclosure
      • Clients don’t need to know whether they are dealing with a component or with an enclosure
  • Inheritance increases number of classes
    • Use composition instead (“has a” )

Transparent Enclosure

  • Two features:
    • Single-child composition
      • Calls its child, then adds its own behavior
    • Compatible interfaces
      • Can use the enclosing object in place of the one it encloses
  • Implemented by the Decorator pattern
    • Saw this earlier

158

Class Diagram for GUIFactory

159

Diagram for Product Classes

Abstract Factory Pattern

  • Name
    • Abstract Factory or Kit
  • Applicability
    • Different families of components (products)
    • Must be used in mutually exclusive and consistent way
    • Hide existence of multiple families from clients

Structure of Abstract Factory

162

Abstract Factory: Consequences

  • Isolate instance creation and handling from clients
  • Can easily change look-and-feel standard
    • Reassign a global variable;
    • Recompute and redisplay the interface
  • Enforce consistency among products in each

family

  • Adding to family of products is difficult
    • Have to update factory abstract class and all concrete classes 163

Multiple Window Systems

  • Want portability to different window systems
    • Similar to multiple look-and-feel problem, but different vendors will build widgets differently
  • Solution:
    • Define abstract class Window, with basic window functionality (e.g., draw, iconify, move, resize, etc.)
    • Define concrete subclasses for specific types of windows (e.g., dialog, application, icon, etc.)
    • Define WindowImp hierarchy to handle window implementation by a vendor 164

Implementation

165

Bridge Pattern

  • Name
    • Bridge or Handle or Body
  • Applicability
    • Handles abstract concept with different implementations
    • Implementation may be switched at run-time
    • Implementation changes should not affect clients
    • Hide a class’s interface from clients
  • Structure: use two hierarchies
    • Logical one for clients,
    • Physical one for different implementations

170

Command Objects

171

Command Pattern

  • Name
    • Command or Action or Transaction
  • Applicability
    • Parameterize objects by actions they perform
    • Specify, queue, and execute requests at different times
    • Support undo by storing context information
    • Support change log for recovery purposes
    • Support high-level operations
      • Macros

Structure of Command Pattern

Command Pattern

  • Consequences:
    • Decouple receiver and executor of requests
      • Lexi example: Different icons can be associated with the same command
    • Commands are first class objects
    • Easy to support undo and redo
      • Command must have method to check whether it’s reversible
      • Must add state information
    • Can create composite commands
      • Editor macros
    • Can extend commands more easily

174

Command Pattern

  • Implementation notes
    • How much should command do itself?
    • Support undo and redo functionality
      • Operations must be reversible
      • May need to copy command objects
      • Don’t record commands that don’t change state
    • Avoid error accumulation in undo process 175

Comparing Objects

  • Java has two designs for objects that can be

(totally) ordered

  • These are things for which sorting makes sense
  • E.g., strings, integers, etc.

Comparable

public interface Comparable { // Returns negative integer, zero, or a positive integer if this object is less than, equal to, or greater than o. public int compareTo(Object o); }

  • Advantages and disadvantages?
    • Can only implement one compareTo operation
    • No extra levels of indirection; objects know how to compare themselves

Comparator

public interface Comparator { int compare(Object o1, Object o2); }

  • Advantages and disadvantages?
    • Can have multiple comparison operations
    • An example of delegation
    • Comparator needs to know innards of your objects
      • Can make the Comparator implementer an inner class
    • Extra indirection; more objects floating around