我是使用模式编程的新手,我花了几个小时寻找模式观察器的 Smalltalk 实现的示例,但徒劳无功。
如果有人能提供我在 Smalltalk 下实现这种模式的具体示例,我将不胜感激。
最佳答案
Smalltalk 中观察者模式的标准实现是#changed
/#update
机制。
它是这样的:
subject addDependent: anObserver.
subject changed.
然后
anObserver
获取发送 #update
:MyObservingObject>>update
"I got called in a #changed chain"
super update.
self doUpdatingStuff
您可以使用
#changed:
进行更好的控制和 #update:
(注意冒号):subject addDependent: anObserver.
subject changed: subject.
和
MyObservingObject>>update: anObject
"I got called in a #changed: chain"
super update: anObject.
self doUpdatingStuffWith: anObject
但是,通常会发现使用符号来表示更改的内容:
subject addDependent: anObserver.
subject changed: #myNumbers.
和
MyObservingObject>>update: anObject
"I got called in a #changed: chain"
anObject == #myNumbers ifTrue: [
self doUpdatingStuffForNumbers.
^ self "inhibits the super"].
super update: anObject.
当你看Squeak或 Pharo ,你至少会发现另外三个
观察者实现:
Morph>>#on:send:to:
)Object>>#when:send:to:
和 Object>>#triggerEvent:
您可以找到 comparison其中在 Signals project ,另一种实现,但受到 Qt 的启发。
关于observer-pattern - 在 Smalltalk/VisualWorks 中实现观察者模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17082576/