Oberserver design pattern: difference between notify and update - java

Hello I am trying to implement an analog clock using the Observer design pattern. I have understood the theory of how it works but when I was coding I couldn't understand the difference between notifyObserver (Observable) and update (Observer), more specifically: when and where do we use notify versus when and where do we us update? They seem to have the same purpose of letting know the observes that something in the program has changed, but they do it differently, which is what I don't quite understand.
Also, I haven't understood very well where the addObserves method needs to be put in order for it to observe.

when and where do we use notify versus when and where do we us update
notifyObservers is an Observable method which has the responsibility to iterate through all the observers registered with it and call their individual update method.
update method belongs to the Subjects which contain the actual logic of what needs to be done for individual Subjects when the notification happens. This can be different for different subjects. You can read more here on this subject.

Related

Java: Can an Observer be notified of changes through a hierarchy of observers?

So I have a few classes that are just Observers, another that is both an Observer and Observable, and a third that is just Observable.
I want to be able to take the class that is both and notify some of the Observers that the class that is only Observable has changed. So, the Observer and Observable class doesn't actually change itself, but notifies the Observers when the Observable only one does (and thus, gets the observers to run their update method).
Is this something possible to do? Is is it a must to change the Observable in order to make it notify the observers? How would I even go about this?
Edit: I discovered the issue with my design:
When the update method takes an Observable o, I wasn't ensuring whether this o was an instance of ObserverObservable or ObservableOnly, so problems arose from that. I had to make conditions for both and create an instance of ObservableOnly or a class/methods that gets information from Observable only to be a field within Observer.
As earlier stated, it is definitely possible.
I took some time to write some simple code, where I use java interfaces for both the observer and the observable. (I guess it's worth mentioning that I'm using the poll version of observer, not push.)
http://pastebin.com/M2CY82wd
The code is not perfect, but hopefully it shows you what it could look like.
Also, here is a book that I, and many others, recommend:
http://shop.oreilly.com/product/9780596007126.do
Sure, you can do this.
Some questions you should ask yourself to clarify your design:
Why should the Observer-only class not observe the Observable-only class directly?
How can the Observer-only class learn about details of how the Observable-only class changed?
Is the Observer-and-Observable class only responsible for forwarding the update notifications, or has it also some other role in your design?
Codewise, I see no problem having a class that has the behavior of both an observer and a subject. If you're working with interfaces, the observer/observable should just implement both interfaces.
To have both behaviors in one class should not be a problem if your overall implementation is clean, Feel free to submit some code, and we can comment on it from a Design Pattern point of view.
I read about something that might be of use but haven't implemented it myself.
In brief you would be creating a 'linked observer' chain where each observer can hold a 'observer' variable next_, and when you notify the observer of change you would recursively walk through linked Observers.
while (observer != NULL)
{
observer.onNotify(entity, event);
observer = observer.next_;
}
The actual article that read was here;
http://gameprogrammingpatterns.com/observer.html#linked-observers

OOP Class being an Observerable and Observer

I have a problem whereby I have a class Item, which has a list of Subitems. When a child item has been changed or deleted, I need the parent Item to know about it.
I was thinking that the Observer pattern would come in handy here. But does it make sense for an Item class to both extend extend Observerable and implement Observer?
Cheers.
Yes it makes sense sometimes to have an observer also be observed.
Ask yourself why you want to apply the pattern, however. Observing just to give updates might be more complicated to debug, compared to just updating directly, e.g., the child calls his parent when he updates.
Generally, Observables don't want to know the details about their Observers (decoupling, information hiding) so that you can make virtually any class an Observer. If that is what you need, then the pattern is good for you. If not, then adding this may result in needless complexity (harder to understand and debug the code).
Edit (I had this backwards): Do your child (Observable) items already know all the details about their parents (Observer)? If they do, then using Observer might be over-design. If children don't want to know the details of their parent, then Observer could be useful.
When making observers be observable, watch out for cycles https://stackoverflow.com/a/964820/1168342
Your argumentation and situation make sense to use Observer Design pattern. There is very handfull article about Oberver design pattern. There is also very simple example in java so there is no sense to paste it here. Please look on it.
The simplest answer is when you find that you have events flowing in both directions, most likely it is time to introduce a Mediator. Sometimes these objects are coordinators. Most people consider the Controller in MVC a Mediator.
The alternative is to create a peer protocol, which is maybe less structured, and more elastic in that you can do things like discovery that are generally not part of Mediator as it knows the parties it's coordinating in advance.
So my answer would be just making every thing observe various aspects of other things in its ecosystem will lead to chaos pretty quickly unless some kind of communication protocol is in place.
If you need to add a subitem to an item or remove one from it, you have to call a method on that item instance. The methods could look like:
public void addToSubitems(Subitem subitem);
public void removeFromSubitems(Subitem subitem);
So the item stays responsible for managing its subitems. When returning a collection of subitems from the item, always return an unmodifiable collection. By making the Item class responsible for managing the items, it has the possibility to take aktions on addition, removal, etc.
If the item also needs to get notified about changes of its subitems, you can also consider making the subitems immutable and implementing a change as an atomic replace of an items subitem. Or the item will attach an observer to a subitem as soon as it is added to that item.

Observer Pattern: could event processor affect subject execution?

There are several incarnations of Observer pattern: Listeners, Events etc. (am I right?)
But today we found we have no agreement among team members - is it possible that Listener (Observer) affect execution of the method which invokes it.
The example was proposed as following: when the deal is saved via DealDao, it could fire an event which would be caught by some Listener which will:
update calculated fields in the deal (some fees etc.);
create some dependent entities.
I myself greatly dislike this approach - for example because if update of dependent entity in the listener throws an exception, the deal update should be rolled back too.
But it seems unnatural that Listener forces the subject to roll back.
In general if you are changing the behavior of the object then you may be implementing the Strategy Pattern not the Observer Pattern.
Modifying the model itself in response to observed events on it can lead to very complicated behavior so I wouldn't really recommend it but it is valid.
Generally try to think about the "flow" of data and operations through your system. If you can make the flow always go in one direction (or at least have as few loops as possible) then the whole thing becomes a lot more simple to manage and understand.
Adding an observer is "down flow" from the original data. If that observer then goes back and modifies the original data then that is flowing upstream and makes the behavior of your whole program a lot more complicated. For example what happens if that change then triggers another event, which then comes back into the same observer again, etc? Someone tracing through the execution is going to find unexpected data changes until they find that observer and you run into the potential for recursive loops that stack overflow and all sorts of similar fun and games.
If there are no listeners to DealDao, will the deal be saved at all?
If yes, then you actually have an implicit listener which actually does saving operation. Then, when another listener is added which updates fields in the deal, then we have two listeners which operate on the same object. This is clearly violation of encapsulation principle which may cause problems. But Observer Pattern is not in vain: similary, you could get same effect in other way. As user Tim B pointed, first design flow of data with minimum of loops, that is, as a graph with nodes and edges, and let each node be well-defined object (in OOP sense). Only after that, think how to implement it, and Observer Pattern is a valid option.

How to perform different operations within Observer's update() in Java?

I just started playing with Observable, Observer and it's update() method and I can't understand what should I do when different actions call notifyObservers().
I mean, my Observable class has a few different methods that call setChanged() and notifyObservers() in the end. Depending on the called method, some part of the UI (Swing) needs to be updated. However, there is only one update() method implemented in the Observer class.
I though of passing something to the notifyObservers() method and then I can check the argument on update() but it doesn't feel like a good way to do it. Even if it did, what should I pass? A string with a short description of the action/method? An int, like an action/method code? Something else?
What's the best way to handle this situation?
in general you should update everything from the observable when you get a call to update(). if that is not practical, you can pass a hint to notifyObservers().
the gang-of-book says that one of the consequences of the observer pattern is:
"Unexpected updates. Because observers have no knowledge of each other's presence, they can be blind to the ultimate cost of changing the subject. A seemingly innocuous operation on the subject may cause a cascade of updates to observers and their dependent objects. Moreover, dependency criteria that aren't well-defined or maintained usually lead to spurious updates, which can be hard to track down.
This problem is aggravated by the fact that the simple update protocol provides no details on what changed in the subject. Without additional protocol to help observers discover what changed, they may be forced to work hard to deduce the changes.
"
also under implementation, they say:
"Avoiding observer-specific update protocols: the push and pull models. Implementations of the Observer pattern often have the subject broadcast additional information about the change. The subject passes this information as an argument to Update. The amount of information may vary widely.
At one extreme, which we call the push model, the subject sends observers detailed information about the change, whether they want it or not. At the other extreme is the pull model; the subject sends nothing but the most minimal notification, and observers ask for details explicitly thereafter.
The pull model emphasizes the subject's ignorance of its observers, whereas the push model assumes subjects know something about their observers' needs. The push model might make observers less reusable, because Subject classes make assumptions about Observer classes that might not always be true. On the other hand, the pull model may be inefficient, because Observer classes must ascertain what changed without help from the Subject.
"
The second parameter to update() is of type Object, so you can pass anything appropriate. As you note, the approach is rather general. In contrast, a class that maintains an EventListenerList can get a degree of run-time type safety when used as specified.

Does Mediator Pattern work in this situation?

So for my current project, there are basically three main Java classes:
GUI
Instant Messaging
Computation
Essentially, there needs to be full communication, so we've decided to use the mediator approach rather than than allow the GUI to run the entire project.
Basically, the mediator is going to encapsulate the communication. The problem we've run into is how to allow the GUI components to update without building a ton of methods for the mediator to call anytime something completes.
Ex. Say the GUI wants to log in the user, it goes through the mediator to create a thread and log in, but then the mediator has to relay the success/failure back to GUI as well as update a status message.
The other issue is things that need to update the GUI but do not need the moderator. Is it practical to just allow the GUI to create an instance of that class and run it or should everything go through the mediator?
Our original design just had the GUI managing everything, but it really killed reusability. Is there a better design method to use in this case?
If you're finding Observer to bring too much overhead, Mediator may be the best way to go. I definitely think that you shouldn't have the GUI run the show. If you're going to use the Mediator pattern, the mediator itself should be in charge. Something you might consider is a variant of the Command pattern. If you were using Ruby, I might recommend passing function callbacks around as a means of avoiding having the mediator contact the GUI for every little thing. But since it's Java, some form of encapsulating an action in Command pattern style may help.
If you don't want the callback/notification to be triggerd by the mediator, you can inject the callback into the login function and have login call it when it finishes.
I don't know how you would go about injecting the callback in Java, though. In a language where functions are first class citizens, you could just pass the function, but you're in Java so I guess you will have to use the command pattern as kmorris suggested.
You might also try having the GUI give the mediator a callback object that handles retrieving return values or setting whatever values you need (a version of the Command pattern). There would then be one per call from the GUI to the mediator.
Another thought is to group the methods the mediator calls into semantically related chunks. In particular if the mediator has sections where it tends to call several GUI methods in a row:
gui.a()
gui.b()
gui.c()
you can create a single method that handles the result of calling all three. The advantage of semantically grouped methods (i.e. setFileInformation over setFileMenu, setTab, etc.) is also then if you need to change the GUI, the contents of the methods might change, but the call the mediator makes may not.

Categories