【编程思想】【设计模式】【行为模式Behavioral】访问者模式Visitor

本文通过Python代码示例介绍了一种设计模式——访客模式。该模式将算法从对象结构中分离出来,允许为对象结构定义新的操作而无需修改对象结构本身。文中详细解释了如何实现这一设计模式,并提供了具体的运行输出。

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转载版

 

转载于:https://www.cnblogs.com/demonzk/p/9035681.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值