0
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. 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.

So create observable for every such scenario will be a good practice right?

jaco0646
  • 11,033
  • 7
  • 47
  • 64
  • 2
    `java.util.Observable` is deprecated since Java 9 … – tquadrat Mar 11 '20 at 08:23
  • @tquadrat, while the Java implementation is deprecated, the [pattern](https://refactoring.guru/design-patterns/observer) itself remains very useful. Java simply didn't do a good job of implementing it. – jaco0646 Mar 11 '20 at 15:59
  • @jaco0646: I have no doubt that the Pattern is extremely useful, but when the question is whether creating `Observable` is a good practice (with an explicit reference to the class in the sample), it must be allowed to say that this class is deprecated. The question was *not only* regarding the pattern … – tquadrat Mar 12 '20 at 00:18
  • @tquadrat, there is no `import` statement in the sample. It could be `my.custom.Observable`. – jaco0646 Mar 12 '20 at 00:29
  • @jaco0646: Confessed, but I know the book Anshul refers to ("*Head First Design Patterns*"), and they use `java.util.Observable` with exact the code he provided in the question … – tquadrat Mar 12 '20 at 00:38
  • 1
    Well, in that case, [Observer is deprecated in Java 9. What should we use instead of it?](https://stackoverflow.com/questions/46380073/observer-is-deprecated-in-java-9-what-should-we-use-instead-of-it) – jaco0646 Mar 12 '20 at 17:51

1 Answers1

1

So create observable for every such scenario will be a good practice right?

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!

jaco0646
  • 11,033
  • 7
  • 47
  • 64