访问者模式

# 访问者模式适用于数据结构相对稳定的系统,将作用于结构上的操作解耦,使得操作集合自由演化,增加数据结构困难,增加操作简单。
class Node(object):
    pass


class A(Node):
    pass


class B(Node):
    pass


class C(A, B):
    pass


class Visitor:
    def visit(self, node, *args, **kwargs):
        for cls in node.__class__.__mro__:
            method_name = 'visit_' + cls.__name__
            method = getattr(self, method_name, None)
            if method:
                return method(node, *args, **kwargs)
        return self.generic_visit(node, *args, **kwargs)

    def generic_visit(self, node, *args, **kwargs):
        print("通用类调用:" + node.__class__.__name__)

    def visit_B(self, node, *args, **kwargs):
        print('B类调用:' + node.__class__.__name__)


def main():
    a = A()
    b = B()
    c = C()
    visitor = Visitor()
    visitor.visit(a)
    visitor.visit(b)
    visitor.visit(c)


if __name__ == '__main__':
    main()

你可能感兴趣的:(访问者模式)