How to implement delegate pattern (like in objective-c ) in java
delegates, design-patterns, ios, java, objective-c
Solution
I think there are many ways ways to implement delegation pattern in Java, but probably none which feels like a built-in.
Take a look at the Wikipedia example. Your basic option is to manually implement an interface, and then simply forward the calls to a concrete instance which you can change during run-time as much as you wish.
Now depending on what tools you have and can use, you can make this forwarding more automatic. One idea, is to use aspect-oriented programming, like AspectJ.
Having an aspect compiler (or runtime) you could utilize annotations and come up with a simple extension to the language:
class Person {
@Delegate Animal animal;
...
}
You'd then have to write an aspect that finds `@Delegate`s and automatically adds forwarding methods in the class'es (eg. `Person`) interface.
If you are able to use a more groovy JVM language, then you wouldn't even have to write a single line of code, because such languages have delegates in the standard library:
You can have a look here, to see how it's done in Groovy. (essentialy exactly like the `Person` example syntax I came up with... but built-in!)
Problem
I looked at an example where delegation pattern is explained for java. Didn't find much use for it (excuse the ignorance) as i feel it lacks the flexibility in objective-c. Is there way to dynamically set the delegate object as one can do in objective-c. Isn't that the whole point of delegation? My knowledge of java is very preliminary , so please explain a bit in detail.