SICP 全笔记

Exercise 2.76. As a large system with generic operations evolves, new types of data objects or new operations may be needed. For each of the three strategies–generic operations with explicit dispatch, data-directed style, and message-passing-style–describe the changes that must be made to a system in order to add new types or new operations. Which organization would be most appropriate for a system in which new types must often be added? Which would be most appropriate for a system in which new operations must often be added?

新类型

当添加一个新的类型的时候,三种编程类型的比较如下。

  1. explicit dispatch 需要在过程中新加入一个 if 的判断语句
  2. data-directed 需要在表中新加入一列(即对每个操作都需要一个过程来描述对于这个新的类型应该怎么办)
  3. message-passing-style 新建一个过程,在过程中添加对数据的操作

新操作

当添加一个新的操作的时候,三种编程类型的比较如下。

  1. explicit dispatch 需要新添加一个过程,对每种类型都需要写 if 来判断
  2. data-directed 需要在表上添加上一行,即在每种数据类型中,都添加一个过程,然后把过程加入表中。
  3. message-passing-style 需要在每个类型中的 dispatch 里面添加一个过程。

比较

当新的类型常常会被添加进来的时候,使用 data-directed 或者 message-passing-style 都是比较好的解决方案。因为他们都不用修改外部的接口。

当新的操作常常会被添加进来的时候,三种方式都差不多。data-directedmessage-passing-style 需要为每一种类型(例如之前的每一个package)添加相应的操作,explicitly dispatch 也只需要为这个新操作去判断每一种数据类型。但对于成百上前个数据类型的话,恐怕三种方式都使得系统难以维护。