next up previous
Next: About this document ...

  1. (10 points) Give short answers for the following questions:

    1. Give two motivating reasons for why or when a developer might use the Visitor Design Pattern.








    2. What role does polymorphism and virtual functions play in the Visitor Pattern.








    3. How does double dispatch work in the Visitor Pattern: which classes initiate the dispatch and which classes issue the second dispatch? Why is it needed?








    4. What's the motivation behind the Chain of Responsibility Design Pattern?








    5. When should you use the Proxy Design Pattern.

  2. (10 points) Give the output for the follwoing Python program:

    import string
    class Music:
      def __init__(self):
        self.wds = []
        self.L = [
                  "There's never been such grave a matter",
                  "As comparing our new brand name black sunglasses",
                  "All these poses such beautiful poses",
                  "Makes any boy feel as pretty as princes"
                 ]
    
      def stuff(self, num=15):
        for count in range(0, len(self.L)):
          self.wds += string.split(self.L[count], ' ')
        while self.wds:
          print self.wds[0:num]
          self.wds = self.wds[num:]
    
    if __name__ == '__main__':
      M = Music()
      # Node that we're overriding the default param value:
      M.stuff(3)
    








  3. (10 points) Give the output for the following Python program:

    list = [7, 4, 9]
    fun = lambda x: x*x
    print map(fun, list)
    

  4. (10 points) Rewrite the previous Python program so that it doesn't use either lambda functions or the map function.

  5. (10 points) Give the output for the following Python program:

    class Artist:
       def __init__(self, name):
          self.artist = name
       def __repr__(self):
           return self.artist
    
    class Music:
       def __init__(self):
          self.song = 'Yeah'
          self.artist = Artist('Usher')
    
       def __call__(self) :
          print "Artist: ", self.artist
    
       def display(self):
          print self.song, '\t', self.artist
    
       def default(self):
          print "Whoa...no way."
    
       def dispatch(self, fn):
          fun = getattr(self, fn, self.default)
          fun()
    
    if __name__ == "__main__":
       music = Music()
       music.dispatch('display')
       music.dispatch('print')
       music()
    

  6. (10 points) Listed below is a Shape hierarchy that uses the Visitor pattern, where the Visitor is illustrated on the next page. Rewrite line 28 so that it calls a function that performs the same functionality as line 28 but without the use of the map function.

          1 from visitor import *
          2
          3 class Shape:
          4   def __init__(self, msg):
          5      self.msg = msg
          6
          7 class Rectangle(Shape):
          8   def __init__(self, msg, u, w, h):
          9      Shape.__init__(self, msg)
         10      self.upperLeft = u
         11      self.width = w
         12      self.height = h
         13   def __repr__(self):
         14      return self.msg+": "+"("+ str(self.upperLeft)+", "+\
         15         str(self.width)+", "+str(self.height)+")"
         16
         17 class Circle(Shape):
         18   def __init__(self, msg, c, r):
         19      Shape.__init__(self, msg)
         20      self.center = c
         21      self.radius = r
         22   def __repr__(self):
         23      return self.msg+": "+"("+str(self.center)+\
         24         ", "+str(self.radius)+")"
         25
         26 def visit_shapes(shapeList):
         27    print '(1) Printvisitor: Print the shapes'
         28    map(PrintVisitor(), shapeList)
         29    print 'Areas are:', map(AreaVisitor(), shapeList)
         30
         31 if __name__ == "__main__":
         32    rec = Rectangle("rectangle", (-5,5), 4, 5)
         33    circle = Circle("circle", (3,4), 5)
         34    shapeList = [rec, circle, Rectangle("rectangle",(-1,-1),1,1)]
         35    visit_shapes(shapeList)
    

  7. (20 pts) Listed below is a Visitor hierarchy that implements a Visitor for the Shape hierarchy on the preceding page. Write an AreaVisitor so that the use of the AreaVisitor on line 29 of the Shape hierarchy works.

    import math
    
    class Visitor:
       def __init__(self): pass
    
       def dispatch(self, visitedObject) :
          """ Figures out what method to call based on the object's class """
          klass = visitedObject.__class__
          methname = 'visit' + klass.__name__
          meth = getattr(self, methname, self.default)
          return meth(visitedObject)
       
       def default(self, visitedObject):
          """ This gets called if you haven't defined a visitor for the class """
          print 'I can\'t visit this thing:', visitedObject
            
       def __call__(self, visitedObject) :
          """ Make it so you can use the class name like a function-call """
          return self.dispatch(visitedObject)
    
    
    class PrintVisitor(Visitor):
       """ A simple visitor that just prints out the object it visits """
       def __init__(self):
          Visitor.__init__(self)
       def visitCircle(self, circle): 
          print 'CIRCLE: ', circle
       def visitRectangle(self, rectangle): 
          print 'RECTANGLE: ', rectangle
       def startVisit(self, visitedObjectList):
          map(self.dispatch, visitedObjectList)
    

  8. (20 pts.) The find_full_id function does not appear to function correctly in the Tree.py program that we used for Assignment # 3. Write a function, findNode(dir, name, foundNode), that accepts three parameters: a parameter for the directory to start the search, dir, a parameter for the file name that you're searching for, name, and a parameter for a set that returns the file names that match the search, foundNode. You can use routines in the Tree.py program. Your findNode function should search all files and directories contained in the root dir. The following code segment illustrates how the findNode function might be used:

    def doFind(tree):
        if tree == None: return
        result = tkSimpleDialog.askstring('search', 'File to search for: ')
        print "Doing find for: ", result
        #foundNode = tree.find_full_id([os.getcwd(), result])
        foundNode = findNode(rootNode, result, foundNode)
        if foundNode == None or len(foundNode) == 0:
            print result, " Not found"
        else:
            print "Found node is: ", foundNode[0].id
    




next up previous
Next: About this document ...
Brian Malloy 2006-06-25