zoukankan      html  css  js  c++  java
  • 【编程思想】【设计模式】【行为模式Behavioral】访问者模式Visitor

    Python版

    https://github.com/faif/python-patterns/blob/master/behavioral/visitor.py

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    """
    http://peter-hoffmann.com/2010/extrinsic-visitor-pattern-python-inheritance.html
    
    *TL;DR80
    Separates an algorithm from an object structure on which it operates.
    """
    
    
    class Node(object):
        pass
    
    
    class A(Node):
        pass
    
    
    class B(Node):
        pass
    
    
    class C(A, B):
        pass
    
    
    class Visitor(object):
    
        def visit(self, node, *args, **kwargs):
            meth = None
            for cls in node.__class__.__mro__:
                meth_name = 'visit_' + cls.__name__
                meth = getattr(self, meth_name, None)
                if meth:
                    break
    
            if not meth:
                meth = self.generic_visit
            return meth(node, *args, **kwargs)
    
        def generic_visit(self, node, *args, **kwargs):
            print('generic_visit ' + node.__class__.__name__)
    
        def visit_B(self, node, *args, **kwargs):
            print('visit_B ' + node.__class__.__name__)
    
    
    a = A()
    b = B()
    c = C()
    visitor = Visitor()
    visitor.visit(a)
    visitor.visit(b)
    visitor.visit(c)
    
    ### OUTPUT ###
    # generic_visit A
    # visit_B B
    # visit_B C
    Python转载版
  • 相关阅读:
    数值拓展与函数拓展
    正则小记
    Struts2(三)配置详解
    Struts2(二)工作原理
    Struts2(一)基本配置
    Eclipse新建动态web工程项目出现红叉解决方案
    Spring系列之AOP
    Java动态代理的实现机制
    Spring系列之装配Bean
    Spring系列之基本配置
  • 原文地址:https://www.cnblogs.com/demonzk/p/9035681.html
Copyright © 2011-2022 走看看