Pages

Friday, October 26, 2012

Visitor design pattern in python

Visitor pattern uses double dispatch which is simple but powerful.
class Node:
    def __init__(self):
        self.children = []
    def add(self, node):
        self.children.append(node)
    def printIt(self):
        print("Node")
    def accept(self, visitor):
        visitor.visit(self)
        
class NodeA(Node):
    def printIt(self):
        print("NodeA")
        
class NodeB(Node):
    def printIt(self):
        print("NodeB")
        
class NodeVisitor:
    def visit(self, node):
        node.printIt()
        if len(node.children) > 0:
            for child in node.children:
                child.accept(self)
        
if __name__ == "__main__":
    n = Node()
    n1 = NodeA()
    n2 = NodeA()
    n3 = NodeB()
    n4 = NodeB()

    n1.add(n3)
    n1.add(n4)
    n.add(n1)
    n.add(n2)
    
    v = NodeVisitor()
    v.visit(n)
Node -+- NodeA -+- NodeB
      |         +- NodeB
      +- NodeA
2012 10 27 01 32 49
Node
NodeA
NodeB
NodeB
NodeA

No comments:

Post a Comment