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.
Related
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.
I have an Event Login. I plan to populate that event with information such as this:
// Class A.
Login login = new Login();
login.setUsername(userName);
observer.notifyEvent(login);
The idea is for class B to get this information.
Is this bad practice? If so why?
The only forseable problem is that some other part of the software will be listening to this for no reason. When in reality only one class should be getting the information.
The only advantage is that all my classes are connected to the Observer object, but not connected to each other. In other words, if I wanted to pass the username I would need to connect A and B. Which I would only do in extreme circumstances.
Not much of a problem. - However, you may want to include the "sender" of the event in the event object so that the listener can identify where it comes from and, if needed, can get further state information from the event source.
The Observer pattern allows you to decouple the source of the event from the consumers of an event.
This is generally a good idea, even if you are only going to register one consumer.
However, I'll recommend you not to use the java.util.Observer which uses plain java.lang.Object as events, which means you must check the event object via instanceof and cast to the appropriate class.
I think its better to use an Observer or Listener implementation which supports generic types, such as Spring's ApplicationListener or Guava's EventBus which allow you to register Listener for events of particular class type, such as Login.class in your example.
Well, you probably need to dive a bit deeper into the original GoF book. For such a situation when a developer cares about different components that might be interested in different types of events the book offers the subjects collection that is maintained by the ChangeManager.
So when a component is interested in a specific type of event it passes a specific subject to the Register method so that this component won’t receive the updates for the events that represent a different subject. Additional advantage is the further decreasing of coupling.
Alternatively you might end up with building the system where any component that is plugged to the wire listens to all the events but that solution is too generic and adds lots of risks to the implementation (e.g. in the runtimes with automatic memory management like .NET the garbage collector won’t collect the subscriber while it is listening to any event – just because the ChangeManager still maintains a reference to it). It adds an additional responsibility to the subscriber - it has to do the additional filtering of events analyzing their type.
The rule of thumb is that you don’t need to subscribe for a specific event if you’re not interested to be notified when it occurs.
Referring to your example it is much better to introduce the Login subject and not to subscribe to it any component that is not interested in this specific subject.
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.
I have a question about the state pattern and how to implement it using DDD.
For what I understand of the state pattern, the pattern is used to handle the transition between different states, so its the responsibility of each state to handle what the system has to do to transit to the new state.
To do so, using polymorphism, each state can be a class of its own that extends one base class, implementing the transitions from one state to the other, following a graph that defines the possible transitions.
I've been looking for information on how to do this using DDD and, among other web sites, I found this one that uses enums.
http://nurkiewicz.blogspot.co.uk/2009/09/state-pattern-introducing-domain-driven.html
The reason for using enums is that you can persist the current state, in this case the name of the enum, to a repository, so your aggregate can be recreated later. So, following the state pattern definition, the state can receive different parameters (for example, the new value of a field) so the context (in this case the aggregate) can transit to the new state and update its fields so the state is consistent. This means, the state would be the one responsible to update the values of the aggregate.
My question is, is this the right thing to do? For what I understand, in DDD the aggregate is the one that knows about its internals and, whenever an entity inside the aggregate has to be changed, the aggregate has to expose a method which later on would call the entity to change its value. This way the entities are encapsulated inside the aggregate and they cannot be accessed directly from outside it.
But using this implementation of the state pattern it's the entity (or value object, I don't know how to call the state) who changes the aggregate. You can even use the enum directly and call an operation inside it passing your aggregate and the aggregate would be changed.
Another question about this is; the moment you have to provide some behaviour to your aggregate that depends on the current state, where do you do the implementation? Inside the aggregate, adding more operations to the base class of the state to check if the state is one or the other? Or inside the state, so the state uses the aggregate to call the different methods that it exposes to provide that functionality? The first approach would mean that, depending on the number of states you have, you would have create many methods just to check if you are in the correct state for your purposes. The other one would imply that is again the state who coordinates the way the aggregate has to call its internals.
Sorry if this question has being asked before. I've looking for days and I couldn't find something similar to what I'm asking here.
Thanks in advance.
EDIT:
Sorry for the late response, I was on holidays.
In my case the states are rather simple. They would reflect the different states of a tournament (NEW, OPEN_REGISTRATION, CLOSED_REGISTRATION, IN_PROGRESS, FINISHED, CANCELLED). What I'm trying to do is a probe of concept following the approach from the link I provided.
My question here is: the moment the aggregate (context) has to do something that depends on the state (like register a player), where would you hold that logic? Inside the context, checking first if the state class is of type OpenRegistrationState? Or inside the state classes, providing an implementation inside the OpenRegistrationState that stores the player into the context (the method would expect both the context and the player as parameters) and throwing and exception from the other ones?
It seems like using the second approach, the logic inside the context is quite simple, it only has to call the current state to do the job for it. The problem is, the moment you have many different methods that relies on the state to operate, your state classes would have an explosion of different methods that only one or two of them would implement while the other ones would throw an exception. In that case, I don't know if it would be easier to forget about the state pattern and just use an enum and check the value whenever some logic depends on the current state.
The state pattern's context says that an object's behavior is dependent on its state, and its methods contain if/then (or case) logic reflecting conditions based on states. The pattern provides an alternative to those case statements.
The solution is to create classes for each state, implementing a common interface. State-dependent operations are delegated from the context object to its current state object. The context object points to a state object that reflects its current state.
So, if I understand your question, then Domain objects (à la DDD) are the context objects and you want to avoid case logic in them. Otherwise, you don't need the state pattern (and you can stop reading now if you want, since the rest doesn't apply).
Craig Larman's Applying UML and Patterns 3rd Edition book has a chapter on Designing a Persistence Framework with Patterns and a section on Transactional States and the State Pattern. I believe his approach is compatible with DDD as it has been defined here. Actually, it's a variant of the PersistentObject idea from Scott Ambler
Domain classes have state. In this example, the states are about persistence: New, OldClean, OldDirty, OldDelete and Deleted. See Larman's book for the details.
A couple of details I couldn't easily annotate on the PlantUML image above:
the PObjectState abstract class has default no-op bodies for each method (transition)
the implementations, e.g., OldDirtyState.commit(...) handle the implementation of the behavior based on state. For persistence, this makes sense since they are generally behaviors that aren't related to domain logic. A rollback of a persistent object is basically the same.
Larman has a footnote stating "Whenever a domain object class extends a technical services class, it should be pause for reflection, as it mixes architectural concerns (persistence and application logic)."
You didn't use a concrete example of what exactly the State is that you want to model, so I am not sure whether this example applies appropriately.
If your State is some cross-cutting concern that introduces unwanted coupling in your domain objects, then you have to ask yourself the question which is worse: Case logic in the Domain objects, or unwanted coupling. Designs are trade-offs and you have to pick your battles.
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.