OOP Class being an Observerable and Observer - java

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.

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

Java Swing GUI User actions handling

How should Listeners etc be managed? I've found only examples with one button etc.
I can think of following options:
Extra class for each - doesn't seem right, especially when items
can be created dynamically
Class for each group (such as form1,
form2, controlButtonsOnLeft, controButtonsOnRight, mainMenu,
userMenu, ...) where I'll check which button/component caused this
(via getSource method for example)
Some super (sized) controller,
which will accept all user actions
New anonymous class for each,
which will call controller's method with parameters specifying
details (probably enums)
And another question: I've found many examples for MVC, I was wondering what is better (or commonly used) for app. developed by 1 person (app will not be huge)?
A. Viewer sets listeners to controller (A1-3)
B. Controller calls viewer's methods, which accepts listener as parameter (methods addLoginSubmitListener, addControlBoldButtonListener etc)
All of above are possible to implement and so far I would choose B4.
Meaning in Control I would do something like this:
...
viewer.addLoginButtonListener(new Listener()
{
#Override
public void actionPerformed(ActionEvent e) {
...
someButtonsActionHandler(SomeButtonEnum, ActionEnum);
...
}
});
...
private void LoginActionHandler(LoginElementsEnum elem, ActionEnum action)
{
if (elem.equals(LOGINBUTTON)) {...}
...
}
...
This combines readable code (1 logic part at one place in code), doesnt create any unwanted redundant code, doesnt require any hardly-dynamic checks, is easily reusable and more.
Can you confirm/comment this solution?
To be honest the question comes down to a number of questions...
Do you want reusability?
Do you want configurability?
Are they self contained? That is, does it make sense for anybody else to listener to the component or need to modify the resulting action of the listener in the future?
Personally, I lean towards self containment. A single listener for a given action/task. This makes it easier to manage and change should I need to.
If I don't need reusability (of the listener) or configurability, then an anonymous inner class is generally a preferred choice. It hides the functionality and doesn't clutter the source code with small, once use classes. You should beware that it can make the source code difficult to read though. This of course assumes that the task is purpose built (its a single, isolated case). Normally, in these cases I will prefer to call other methods from the listener that actually do the work, this allows a certain amount of flexibility and extendability to the class. Too often you find yourself wanting to modify the behaviour of a component only to find that behaviour buried within an anonymous or private inner class...
If you want reusability and/or configurability - that is, the listener performs a common task which can be repeated throughout the program or over time via libraries, then you will need to provide dedicated classes for the task. Again, I'd favour a self contained solution, so any one listener does only one job, much easier to change a single listener then having to dig through a compound list of if-else statements :P
This could also be a series of abstract listeners, which can build functionality for like operations, deleting rows from a table for example...
You could considering something like the Action API (see How to Use Actions for more details), which are self contained units of work but which also carry configuration information with them. They are designed to work with buttons, such as JButtons and JMenuItems, but can also be used with key bindings, making them extremely versatile...
The second part of you question (about MVC) depends. I prefer to keep UI related functionality in the view and out of the controller as much as possible. Instead of allowing the controller to set listeners directly to components, I prefer to provide my own, dedicated, listener for the controller/view interaction, which notifies the controller of changes to the view that it might like to know about and visa versa.
Think about it this way. You might have a login controller and view, but the controller only cares about getting the credentials from the view and authenticating them when the view makes the request, it doesn't care how that request is made from the views perspective. This allows you to design different views for different circumstances, but so long as you maintain the contract between the view and the controller, it won't make any difference...But that's just me.

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.

Why property change listener instead of observable

I was having problems with class design until i found out about observable (using observer design pattern) and thus created a small application using it which solved my problem. I was happy and proud that I had used a good principle to sovle a problem.
Now i am about to start my main application and have just read this
Making a JFrame and Observable Object
Why is the poster advised against the use of observable and instead told to use propertychangelistenr? Is there any issues with using observable?
Regards
Observer and Listener pattern are very similar. But Observer has a weakness: all observables are the same. You have to implement the logic that is based on instanceof and cast object to concrete type into Observable.update() method.
Listeners are different. There are a lot of listener types. For example mouse listener, keyboard listener etc. Each one has several callback methods (i.e. keyPressed(), keyReleased() etc). So, you never have to implement the logic that should answer the question "is it my event" into the event handler.
I think that this is why listener model is preferable.
DejanLekic and others have probably by now realized, that Observable is not an interface. That is the whole problem with Java.util.Observable!
The user of Observable has to inherit from it, and nothing else.
Consider Java.RMI or Listener events.
The only right answer is "it depends".
Observable is good when you don't care what changes about an object; you only want to know that something changed and update e.g. a cache of object properties. It's interface is just too coarse, but it could be a time-saver if you just have a need for such a thing.
On the other hand, as AlexR noticed, you also don't know what type of argument gets passed in before hand (it can even be a null value!). This makes it harder to do something useful with it. A proper listener class can have a richer API, but at the cost of adding a Listener interface and event class to your project.
PropertyChangeListener is a special case of the Observable pattern. That is I guess that both solution is good from a design perspective. Meanwhile as far as I remember PropertyChangeListener has some built in support hence it might require less coding. Ie. see: http://download.oracle.com/javase/1.4.2/docs/api/java/beans/PropertyChangeSupport.html.
The difference is in how you use them. Most of the time subclasses of Observable have no particular implementation - you inherit from it just to get a new type of Observable. Listeners on the other hand implement particular interface (or top level EventListener interface) and therefore MUST implement certain methods.

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.

Categories