Skip to content

vistor模式通常译为访问者模式 #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 21, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions source/c08/p21_implementing_visitor_pattern.rst
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
============================
8.21 实现观察者模式
8.21 实现访问者模式
============================

----------
Expand Down Expand Up @@ -60,7 +60,7 @@
t4 = Add(Number(1), t3)

这样做的问题是对于每个表达式,每次都要重新定义一遍,有没有一种更通用的方式让它支持所有的数字和操作符呢。
这里我们使用观察者模式可以达到这样的目的
这里我们使用访问者模式可以达到这样的目的

.. code-block:: python

Expand Down Expand Up @@ -159,7 +159,7 @@
讨论
----------
刚开始的时候你可能会写大量的if/else语句来实现,
这里观察者模式的好处就是通过 ``getattr()`` 来获取相应的方法,并利用递归来遍历所有的节点:
这里访问者模式的好处就是通过 ``getattr()`` 来获取相应的方法,并利用递归来遍历所有的节点:

.. code-block:: python

Expand All @@ -184,12 +184,12 @@
def do_HEAD(self, request):
pass

观察者模式一个缺点就是它严重依赖递归,如果数据结构嵌套层次太深可能会有问题,
访问者模式一个缺点就是它严重依赖递归,如果数据结构嵌套层次太深可能会有问题,
有时候会超过Python的递归深度限制(参考 ``sys.getrecursionlimit()`` )。

可以参照8.22小节,利用生成器或迭代器来实现非递归遍历算法。

在跟解析和编译相关的编程中使用观察者模式是非常常见的
在跟解析和编译相关的编程中使用访问者模式是非常常见的
Python本身的 ``ast`` 模块值的关注下,可以去看看源码。
9.24小节演示了一个利用 ``ast`` 模块来处理Python源代码的例子。