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.
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 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 have a dialog, which have four buttons say New, Save, Delete, Cancel. Now each of these need to perform their action. So I have defined a separate class which implements an ActionListener. I have used this class to perform each of the button action.
public class MyClass implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().toString() == "OK") {
// Code
} else if( .. ){
}
}
}
What I have done is, I defined an inner class which I used to do the same functionality. But what I was not getting is, is it best practice to write a separate class or is it best to use inner class. I was suggested to write in a public class so tomorrow some one can use this class to perform their action. So I have the following questions,
If the functionality is not called by any object (which I can't say) then I can write it in inner class? OR
Is it a good practice always to write inner class which performs the actions of that dialog?
There is no general answer to these questions. If the code in actionPerformed() is one line, writing a whole class file is usually overkill.
If the code is more complex, it might be suitable to reuse but as the code grows, it also gets more specific (so you can't reuse it anymore).
Try to follow this approach:
Build your application from simple blocks that are independent of each other.
Configure the application by writing code that connects the blocks.
So in your case, you could have helper methods which do the work. Wrap them in Swing Actions; this allows you to use them in all kinds of buttons and menus.
Try to move as much work as possible into the helpers so that the actions become really simple. If in doubt, ask yourself: Is this code part of the work? Does everyone need to do this?
If yes, then the code should go into a work/helper class.
If it's things like UI related checks (visible/enabled), conversion (string to number), validation, etc., it should go into the action.
When you talk about defining an inner class for a GUI listener, I think immediately of using anonymous classes to do the job:
newButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// do the work for a button press
}
});
// similarly for save, cancel, delete buttons:
saveButton.addActionListener(
new ActionListener()
{
// ...
You'll often see this, and I often use this in my own code.
Which you use depends on the structure of your code, for instance:
how much work each listener needs to do
how much code is shared between the handlers
If each handler is short (e.g. just one method call, with all the real work handled within another class method), I'll use anonymous classes this way. But it does look goofy: unfortunately java requires us to define an object to employ a callback method.
It's also a matter of personal preference and coding style.
However, I'd rarely make a new top-level class for a GUI handler as in your example: even if I separate out the class so that I use the same class for each button, I'd define the class within the class file controlling the buttons, either as a non-public top-level class, or as an inner (non-anonymous) class. If the complexity of a GUI callback grows to the point that it deserves a separate class, I'd start looking for places to refactor.
proper way should be Swing Action(mentioned in comment by #Robin), for JButtons Components as most scalable choice, with implementations of interesting methods
most complex GUI is there way to add EventHandler, which fired event and could be compare in String value
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 have a GUI element which is used across several different points in a swing application. When the 'OK' button is pushed I need to run different code in each instance.
I have gotten around this by passing an action listener in each case but as I continue this is getting messy. It would be preferable to pass a block to a method as is possible in Ruby. I am wondering if something similar but clean exists in Java.
Messy code:
Mostly due to needing to call methods on elements of the GUI object. If I pass the ActionListener in the constructor the object doesn't exist yet. I can call a second method in each instance but it isn't preferable.
You have the right idea already. The usual solution for passing arbitrary blocks of code into methods is a Command pattern. If you can show an example of the "messy" code you have now, it might be possible to help you clean it up.
Update Re: Messy Code
If I pass the ActionListener in the constructor the object doesn't exist yet.
An actual code sample would help a lot in giving a good response. At a guess, I would say perhaps you want to look at a Factory pattern? In this case, I'm thinking more of the encapsulation benefits than the polymorphic benefits. Again, just guessing. Seeing code helps.
Passing an ActionListener implementation is probably the best you can do right now.
Java 8 will provide support for "closures", which will greatly streamline the implementation of interfaces with a single, one-argument methods. But, with Java 7 barely coming out, it will be a few years for Java 8.
Java does not support the idea of code-blocks (or functions, for that matter) as first-class citizens. That's why events are done via classes that implement particular interfaces. You seem to be doing something similar already, so perhaps you just need to create your own interface that supports the particular events you want to support.
The solution I have gone with doesn't really address the title of the question properly but suited my needs perfectly. Because:
In my case it is always the same functionality being parsed (ie, the onConfirm functionality) and this functionality is required in each instance.
Each instance requiring unique functionality did not really suit a factory pattern.
I have made my GUI element abstract:
abstract class Element extends JPanel {
...
private final JButton button = new JButton("OK");
protected abstract void onConfirm();
public Element(){
this.button.addActionListener(new ActionListener(){
#Override public void actionPerformed(ActionEvent e) {
onConfirm();
}
});
...
}
}
With several anonymous inner class implementations which each allow me to access the internals of the GUI Element.
this.getContentPane().add(new Element(){
#Override public void onConfirm() {
doStuffWithCommand();
}
});