问题描述
假设我有一个班级广播员来广播某些事件.例如:
Assume I have a class broadcaster to broadcast certain events.Eg:
List<Observers> observers = …
Public void broadcast(Event e) {
for (each observer: observers) {
observer.observe(e);
}
}
然后我有一个名为EventReceiver的类,它可以完成以下操作
Then I have a class called EventReceiver which does the following
public void processEvent(Event e) {
saveToDatabase(e);
broadcast(e);
}
现在:出现了一个新要求,即当Event的类型为"foo"时,我们应该将其保存到数据库中,而不要广播它.
Now: a new requirement comes up, saying that when Event is of type "foo", we should save it to database but not broadcast it.
我应在哪一层过滤?在broadcast.java还是EventReceiver.java中?
At which layer should I filter ? At broadcast.java or in EventReceiver.java ?
例如:
Public void broadcast(Event e) {
If (event != foo) {
for (each observer: observers) {
observer.observe(e);
}
}
}
或
public void processEvent(Event e) {
saveToDatabase(e);
If (event != foo) {
broadcast(e);
}
}
推荐答案
我要说第二个示例 processEvent
.过滤的责任应该来自于代码主体,在决定广播事件之前,它首先处理事件.将事件传递给 broadcast
毫无意义,因为该事件不会或不应该广播.
I'd say processEvent
, your second sample. The responsibility to filter should come from the body of code first processing the event, before you decide to broadcast it. There's no sense in passing off an event to broadcast
which will not, or should not, be broadcasted.
这篇关于带有过滤器的观察者模式,要过滤到什么级别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!