I'm reimplementing a .Net API in Java and the API specifies a whole bunch of events, ehich java doesn't implicitly support.
I'm going to use an observer pattern but due to the number of event I really don't want to clutter the interface.
I was wondering if it was a good idea to declare an "Event" class which has a subscribe method which takes an "EventHandler Interface" and a throw method.
this way I'm not cluttering my parent class with umpteen lists of subscribers because the individual events handle them.
The only issue I can see is with the arguments for the throw command, as different events would have different arguments.
The solutions I've come up with are letting the throw method accept an array of objects or, creating an interface like IEventArguemnts which can be passed to the throw command and handled by the code that has subscribed to the event, this seems to make more sense to me.
I'd appreciate any suggestions for improving this. Or any refinements.
Java has events, and also API support for events. Check out the java.util package. You'll see java.util.EventListener, java.util.EventObject and some others. There are also support classes for maintaining subscribers, etc. The AWT and Swing APIs for example are heavily event-based.
Normally the addXxxListener(XxxListener l) methods (i.e. the subscription methods) would go on the class that's firing the events, not on the event class itself. The event is the message and it's what's being fired from publisher to subscriber.
Why not just use the JavaBeans event model? If all the objects are running in the same JVM, that will work fine.
Peter Coad had some thoughts about improving the Java Observer model. Perhaps you'll find these helpful.
Related
Within Java you can create an Observer-Observable set of classes in which the Observable can call the Observer. You can also in java explicitly reference an owning class instance in a child instance of another class and call the owning class instance's public functions.
Which is the better approach to take? Which is more beneficial in different scenarios, one example being Multi-Threading?
The Observer Pattern should be used whenever you don't know or don't care who is observing you. This is the key-concept in event-driven programming. You don't have any control of who is observing or what they do when you broadcast your events. Like you already mentioned in your comments, this is great for decoupling classes.
An example of a usage could be in a plugin-architecture:
You write a basic mail-server that broadcasts whenever a mail is received. You could then have a spam-plugin that validates the incoming mail, an auto-reply service that sends a reply, a forward service that redirects the mail and so on. Your plain mail server (the observable) doesn't know anything about spam, replies or forwarding. It just shouts out "Hey, a new mail is here" not knowing if anyone is listening. Then each of the plugins (the observers) does their own special thing, not knowing anything about each other. This system is very flexible and could easily be extended.
But the flexibility provided by the Observer Pattern is a two-edged sword. In the mail-server example, each plugin handles the incoming mail in total isolation from each other. This makes it impossible to setup rules like "don't reply or forward spam" because the observers doesn't know about each other - and even if they did, they wouldn't know in what order they are executed or has completed. So for the basic mail-server to solve this problem, It'll need to have references to the instances that does the spam/reply/forward actions.
So the Observer Pattern provides flexibility. You could easily add a new anti-virus plugin later, without having to modify your plain mail server code. The cost of this flexibility is loss of control of the flow of actions.
The reference approach gives you total control of the flow of actions. However you would need to modify your plain mail server code if you ever need to add support for an anti-virus plugin.
I hope this example gives you some ideas of the pros and cons of each approach.
In regards to multi-threading, one approach isn't favorable over the other.
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 this doubt in Java: when people are writing an event listener they implement an interface and they define a particular function in the interface to achieve a particular task. My doubt is instead of implementing an interface can we just define the function with the an appropriate name.
Also, how interfaces help in achieving event listeners?
Because many different classes would want to listen to the same event and Java does not allow multiple inheritance.
The Listener interface gives you a lot a implementation freedom.
This way you don't have to implement a specific function in a specific class. Though implementing an interface seemes to be the same, it isn't. The functionality of a listener is just still ja single function, but the function is usualy in a lightweight object. Yet you are able to implement a lot of program mechanics inside a listener, if you need to.
Also, you can change the listeners at runtime. You can't change an overriden function.
There are a lot of good reasons to use composition (over inheritance) here.
If you really want to understand this, I encourage you to look inside "Heads first: Design Patterns". The "look inside" feature of amazon contains the complete chapter 1, which explains this pattern greatly.
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.
I learned the object-oriented in Java. Now in develop in C#. This means that I never really understood the functioning of delagates but I know how to use them.
Lately I discovered this page http://java.sun.com/docs/white/delegates.html.
If Java is able to create event without delagates is it possible to do the same in C#? Could we imagine writing our own events without writing a single delegate?
(Question already asked in french here)
Yes, you could use a single-method interface instead of a delegate. You'd also need an implementation of the multi-cast nature of delegates, both in terms of add/remove and invoke. It would be tough to have a single class implementing multicast and also implementing Invoke in a typesafe way, however, due to the interfaces having different numbers and types of parameters. You could have a bunch of them of course: Multicast<T>, Multicast<T1, T2> etc. (The same class would handle asynchronous execution too, probably.)
The other pain in the neck is that you could only implement the interface once per class, even if you wanted several different handlers - so you'd have a lot of nested classes.
There's little that's particularly magical about delegates - they're just a very useful abstraction, and with the syntactic sugar of lambda expressions, anonymous methods and expression trees, they're even nicer.
No, you can't do events in C# without delegates. In C#, events are defined as delegates:
An event is a member that enables a class or object to provide notifications. An event is declared like a field except that the declaration includes an event keyword and the type must be a delegate type.
However, you could mimic events using the Observer pattern.
Microsoft's answer to Sun's White Paper is worth reading.
That's a pretty old document and look where it's gotten them. You can do the exact same thing in .NET if you want. All the "Java Way" is doing is taking advantage of inheritance. That's fine but for many the "function pointer" semantic is much more straightforward and less verbose.
Yes you can. You can use predefined delegates. (I'm not sure what's your level of experience and what are you really asking about)
Why on earth would you want to do that?
I mean, if you have a rules engine, or commands that are more than just eventhandlers, then sure: You will want to implement an interface, because you will have state and behavior besides the actual piece of code you want to fire.
But if providing some code to fire when the event is raised, then there's no reason to not use delegates.
Delegates are thin abstractions over method/function pointers and as such they add very little overhead. And IMO, one should not add overhead just for the sake of it.