sicp每日一题[2.76]

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?


对于 explicit dispatch 风格,每添加一种新类型,都需要编写新类型自身的操作函数,并在每个通用操作函数的 cond 中,添加一个新的分支;而添加新的操作,除了编写新的通用操作函数,还需要为每个类型添加类型相关的操作函数。
对于 data-directed 风格,添加一种新类型时,只需要添加相应的 install-new-package 函数,在一个地方编写好新类型自身的操作函数。通过二维表进行分发管理,通用函数本身不用做任何修改;而添加新操作,需要在每个包中添加相应的类型操作函数,并注册到二维表中;无论是添加操作还是类型,都比较简单。
对于 message-passing 风格,它使用一个动态的函数作为分发的依据,要添加新的类型,只需要为新类型添加一个分发函数;但是要添加新的操作,就需要在每个类型的分发函数中,添加一个新的分支,原有类型越多,添加新操作修改的地方就越多。
对于需要频繁新增类型的系统,应该选择 message-passing 风格,因为它新增类型非常简单,不需要修改旧的代码;对于需要频繁新增操作的系统,应该选择 data-directed 风格,添加操作只需要在实现了新的函数后,添加到二维表中即可。

posted @ 2024-11-13 19:30  再思即可  阅读(1)  评论(0编辑  收藏  举报