views:

230

answers:

4

I have a Car object which contains a latitude field and a longitude field. I use the observer pattern so that any time either of these fields change in my application, my car object is notified.
I now find the need to create several other car objects whose default values I wish to have the same as what is the current latitude and the current longitude. I can keep this state in my Notifier object and when a new observer (the new car) registers to listen I can re-broadcast out the values so the new listener will be up to date.
Is this a misuse of the observer pattern, i.e bad design?

+1  A: 

I think this is a textbook example of good use of the Observer Pattern.

Of course, there may be some aspect of this that you have misgivings about. If you explain what your concerns are these could be better discussed.

Andrew Shepherd
Thanks for your response. I'm a bit of a purist, and I was uneasy about broadcasting to all listeners when the value had not really changed.
Tony D
+1  A: 

The only thing that strikes me as dangerous about this approach is that it's easy to code your observers to assume that if they get a notification, something has changed. With the setup you have above, that's no longer true. Therefore your observers will have to check that something truly changed if they are supposed to perform any actions when they receive a notification.

Probably common sense, but also an easy oversight if you're modifying existing code.

Smashd
Yes, similar to my comment above you have articulated my concern.
Tony D
A: 

It would be better if your subject (the object which knows the current latitude and longitude) also exposes a getter method. Any new listener (a new car in your example), right after registration, might get the current values (lat/long) and be informed through the broadcast of any change thereafter. This will avoid needlessly notifying already registered listeners.

Consider that in a common variation of the observer pattern, the subject notifies the listeners that a change has happened, and the listeners then actively query the current value from the subject (hence the need of a getter method).

Stefano Ricciardi
A: 

An Observer pattern is used in one to many relationship. When you want to notify multiple objects, when one object changes state. Your case is a many to one. I believe its a misuse (I may be wrong). Obvious impact is complexity of code. But the side effect could be loss of flexibility. Look at it like this, what changes. If you want to add more Car's you can, without changing the notification receiver. The receiver need now know about your new Car's implementation. All it cares about is the state.

Now, what happens when you want to add more receivers, which will be the most probable case (requirements not thought through :)). In this case all your car objects will need a change to refer to a new receiver.

Still thinking!!!! I know Im missing something here.

Siddharth

Siddharth