Naman
Naman

Reputation: 2373

Delegate equivalent of Obj-C in Java

In Objective-C, for creating and handling a connection (NSURLConnection), it has a delegate, with methods like didConnect, didFailWithError etc, which are called as required. This is good and simple. How does Java handle connection events (or similar things)? Something listener pattern is there, do one has to register for everything to listen? Something automatic callback?

Upvotes: 2

Views: 459

Answers (3)

Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 21986

After all a delegate is just a class that is guaranteed to have some methods so that you can call them, to let it handle some evenets.

So just declare an interface or abstract class with all the methods that you want to be there like didConnect, etc... then the class holding the delegate will just call these methods, and it will be sure that they will be there.

Upvotes: 0

Gabriele Petronella
Gabriele Petronella

Reputation: 108151

There's no direct equivalent of the delegation pattern as intended in Objective-C.

You can achieve pretty much the same results by using the publish-subscribe pattern, implemented in Objective-C by the NSNotificationCenter and in Java by EventListeners and EventHandlers.

Upvotes: 0

Óscar López
Óscar López

Reputation: 236104

In Java, the equivalent mechanism would be that of EventListeners and EventHandlers. The GUI classes are full of examples of their usage. And there's nothing "automatic" about them, you need to explicitly register handlers for the events of interest.

Upvotes: 5

Related Questions