I having a little trouble making use out of annotations in order to invoke the method that the annotation pertains to... I will give an example:
class MyEventHandlers {
#handler(id=“1”)
public doSomething() {
...
}
#handler(id=“2”)
public doSomethingElse() {
...
}
}
....
subscribe(“event1”, new MyEventHandlers, “1”);
//or maybe a better way to do this?!
....
//later, when I detect ‘event1’ I can process the required handler:
process(new MyEventHandlers, “1”)
The idea is, I want to have a way for defining handlers to events, and then linking a events to handlers. (consider for now an event is some string literal).
In all, I am not sure, what is the best style to use for doing what I want. The above is what I think at the moment. If there is better style to achieve this, please suggest.
I suspect that what you want to do, could be more easily implemented with an AOP framework.
But since you might want to do it yourself anyway:
The key to performance is to only use reflection during setup. So when subscribeing, you create a handler descriptor and add it to the listeners for the event. A handler descriptor is basically a java.lang.reflect.Method with an instance to call it on, and some knowledge on how to get event data in i.e. what arguments the method takes.
This way you can implement event triggering by
for (HandlerDescriptor desc : subscriptionMap.get(event)) {
desc.trigger(event);
}
, which should be plenty fast. You can have different HandlerDescriptors for handlers that take event info, ...
You can also make subscribe itself faster, by caching the java.lang.reflect.Methods at a class level (by a handler id key). Such that reflection is only used, when subscribeing a method of a class, not seen before.
What I'm not discussing here (hint: it's API style)
How to name the annotations
How to get context / event data in, you could take a look at JAX-RS for this.
Basically you'll also parse that info at setup time, e.g. by looking at the argument types, so that you don't need to dispatch for this at .trigger() time.
Whether to have subscribe / unsubscribe or return an Unsubscriber from subscribe.
That's the age old event system api style question.
Related
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.
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've read a bunch of articles and readings on Objective-C delegates, trying to understand them. Coming from Java, they seem very much like Java listeners. For example, let's say I had a button in Java. When the button is pushed, I want something to happen. My code might look something like this:
ButtonListener myButtonListener = new ButtonListener();
someButton.addActionListener(myButtonListener);
...
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
}
}
Something like that. In objective-c it seems that I would do something along the lines of calling a setDelegate method for my button and passing it the "listener" as a delegate. The actual button class would then probably check if that delegate responded to some selector (ie. actionPerformed). If I'm thinking about this the right way, it does seem like delegates are just like listeners. Is that correct? Are there any major differences?
Thanks!
You're pretty much on the button there. The only real difference is delegates in obj-c generally implement multiple functions to perform various actions on events regarding the object they are delegating. For example, the UITextViewDelegate has the methods:
– textViewShouldBeginEditing:
– textViewDidBeginEditing:
– textViewShouldEndEditing:
– textViewDidEndEditing:
The only real difference I've found is you can't create your delegates inline, the way you can in java like:
someButton.setOnClickListener ( new View.OnClickListener {
#Override
public void onClick() {
//do stuff
}
});
they are similar, but not identical. a delegation pattern has broader definition, and often implementation defined tasks which can extend beyond listening alone. the tasks can include listening, or the delegate's implementation may be defined as listening (exclusively).
objc delegates are often used to avoid subclassing, and to serve as listeners or data providers. what a delegate does is defined by the protocol - it can serve as much more than a listener. so a delegate could be a data source/provider. it's just a means to offload implementation to another class, to remove from the class what is frequently customized, app-specific implementation.
NSButton/UIButton's already been specialized for this case via target+action mechanisms. you'd use target+action for this specific case.
Delegate is similar as listener or observer, protocol is similar as interface except protocol can define optional functions (aka messages). In Objective C, you can augment an existing class (without its source code) using category to adopt a protocol and make it a delegate, so that you don't need to create new anonymous inner classes at all. You can't do that in Java.
I think that a better Java analog to .NET delegates would be found in the java.util.concurrent pagkage: Callable, Future, Executor.
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.
Working on a project that parses a log of events, and then updates a model based on properties of those events. I've been pretty lazy about "getting it done" and more concerned about upfront optimization, lean code, and proper design patterns. Mostly a self-teaching experiment. I am interested in what patterns more experienced designers think are relevant, or what type of pseudocoded object architecture would be the best, easiest to maintain and so on.
There can be 500,000 events in a single log, and there are about 60 types of events, all of which share about 7 base properties and then have 0 to 15 additional properties depending on the event type. The type of event is the 2nd property in the log file in each line.
So for I've tried a really ugly imperative parser that walks through the log line by line and then processes events line by line. Then I tried a lexical specification that uses a "nextEvent" pattern, which is called in a loop and processed. Then I tried a plain old "parse" method that never returns and just fires events to registered listener callbacks. I've tried both a single callback regardless of event type, and a callback method specific to each event type.
I've tried a base "event" class with a union of all possible properties. I've tried to avoid the "new Event" call (since there can be a huge number of events and the event objects are generally short lived) and having the callback methods per type with primitive property arguments. I've tried having a subclass for each of the 60 event types with an abstract Event parent with the 7 common base properties.
I recently tried taking that further and using a Command pattern to put event handling code per event type. I am not sure I like this and its really similar to the callbacks per type approach, just code is inside an execute function in the type subclasses versus the callback methods per type.
The problem is that alot of the model updating logic is shared, and alot of it is specific to the subclass, and I am just starting to get confused about the whole thing. I am hoping someone can at least point me in a direction to consider!
Well... for one thing rather than a single event class with a union of all the properties, or 61 event classes (1 base, 60 subs), in a scenario with that much variation, I'd be tempted to have a single event class that uses a property bag (dictionary, hashtable, w/e floats your boat) to store event information. The type of the event is just one more property value that gets put into the bag. The main reason I'd lean that way is just because I'd be loathe to maintain 60 derived classes of anything.
The big question is... what do you have to do with the events as you process them. Do you format them into a report, organize them into a database table, wake people up if certain events occur... what?
Is this meant to be an after-the-fact parser, or a real-time event handler? I mean, are you monitoring the log as events come in, or just parsing log files the next day?
Consider a Flyweight factory of Strategy objects, one per 'class' of event.
For each line of event data, look up the appropriate parsing strategy from the flyweight factory, and then pass the event data to the strategy for parsing. Each of the 60 strategy objects could be of the same class, but configured with a different combination of field parsing objects. Its a bit difficult to be more specific without more details.
Possibly Hashed Adapter Objects (if you can find a good explanation of it on the web - they seem to be lacking.)
Just off the top:
I like the suggestion in the accepted answer about having only one class with a map of properties. I also think the behvavior can be assembled this way as well:
class Event
{
// maps property name to property value
private Map<String, String> properties;
// maps property name to model updater
private Map<String, ModelUpdater> updaters;
public void update(Model modelToUpdate)
{
foreach(String key in this.properties.keys)
{
ModelUpdater updater = this.updaters[key];
String propertyValue = this.properties[key];
updaters.updateModelUsingValue(model, propertyValue);
}
}
}
The ModelUpdater class is not pictured. It updates your model based on a property. I made up the loop; this may or may not be what your algorithm actually is. I'd probably make ModelUpdater more of an interface. Each implementer would be per property and would update the model.
Then my "main loop" would be:
Model someModel;
foreach(line in logFile)
{
Event e = EventFactory.createFrom(line);
e.update(someModel);
}
EventFactory constructs the events from the file. It populates the two maps based on the properties of the event. This implies that there is some kind of way to match a property with its associated model updater.
I don't have any fancy pattern names for you. If you have some complex rules like if an Event has properties A, B, and C, then ignore the model updater for B, then this approach has to be extended somehow. Most likely, you might need to inject some rules into the EventFactory somehow using the Rule Object Pattern. There you go, there's a pattern name for you!
I'm not sure I understand the problem correctly. I assume there is a complex 'model updating logic'. Don't distribute this through 60 classes, keep it in one place, move it out from the event classes (Mediator pattern, sort of).
Your Mediator will work with event classes (I don't see how could you use the Flyweight here), the events can parse themselves.
If the update rules are very complicated you can't really tackle the problem with a general purpose programming language. Consider using a rule based engine or something of the sort.