简体   繁体   English

Java 提供 Observable 不是一个好习惯

[英]Java Provided Observable not a good practice

public void update(Observable obs, Object arg) 
{
  if (obs instanceof WeatherData) {
  WeatherData weatherData = (WeatherData)obs;
  this.temperature = weatherData.getTemperature();
  this.humidity = weatherData.getHumidity();
  display();
  }
 }

The above piece of code is from Head First Design Patterns .上面这段代码来自Head First Design Patterns An event is going to fire for every change that occurs, and this will be sent to all the observers whether the event is what they expect or not.每次发生更改都会触发一个事件,并且无论该事件是否符合他们的预期,这都会发送给所有观察者。 The if block helps in letting the code decide which events to handle. if块有助于让代码决定要处理哪些事件。

So create observable for every such scenario will be a good practice right?所以为每个这样的场景创建 observable 将是一个很好的做法,对吗?

So create observable for every such scenario will be a good practice right?所以为每个这样的场景创建 observable 将是一个很好的做法,对吗?

Yes!是的! I have advocated this approach numerous times, for example here , here , and here .我多次提倡这种方法,例如这里这里这里 It perplexes me why people so often implement the Observer pattern with only one event class and then struggle to pass different types of events.让我感到困惑的是,为什么人们经常只用一个事件类来实现观察者模式,然后努力传递不同类型的事件。 By all means: create new event classes!无论如何:创建新的事件类!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM