[Tutor] Design - Visitor pattern

Alexandre Ratti alex@gabuzomeu.net
Mon, 20 May 2002 16:06:54 +0200


Hello,


while reading up on Demeter law, I came across the Visitor pattern.

"Represent an operation to be performed on the elements of an object 
structure. Visitor lets you define a new operation without changing the 
classes of the elements on which it operates."

	Source: http://c2.com/cgi/wiki?VisitorPattern

I tried to reimplement it in Python based on a Java example.

=> Is this implementation correct?
=> In what kind of situation whould you use it in Python?


Cheers.

Alexandre


##
class Element:

     def accept(self, visitor):
         visitor.visit(self)

class Employee(Element):

     def __init__(self, name, salary, sickDays, vacDays):
         self.name = name
         self.salary = salary
         self.sickDays = sickDays
         self.vacDays = vacDays

class Visitor:

     def visit(self, theClass):
         raise NotImplementedError

     def getResult(self):
         raise NotImplementedError

class VacationVisitor(Visitor):

     def __init__(self):
         self.totalDays = 0

     def visit(self, employee):
         self.totalDays += employee.vacDays

     def getResult(self):
         return self.totalDays

if __name__ == "__main__":
     A = Employee("A", 100, 2, 5)
     B = Employee("B", 110, 3, 6)
     C = Employee("C", 120, 4, 7)

     vac = VacationVisitor()
     for employee in A, B, C:
         employee.accept(vac)
     print vac.getResult()
##

Source: http://www.ciol.com/content/technology/sw_desg_patt/101110501.asp