Answer the question
In order to leave comments, you need to log in
Is there a nice construct for delegating the implementation of an interface?
Let's say we have an interface:
public interface I {
int a();
int b();
}
public class IR implements I {
@Override
public int a() {
return 1;
}
@Override
public int b() {
return 2;
}
}
public class A implements I {
IR delegat = new IR();
@Override
public int a() {
return delegat.a();
}
@Override
public int b() {
return delegat.b();
}
}
public class B extends IR {
}
class B implements I {
IR delegat = new IR();
implements I by delegate;
}
Answer the question
In order to leave comments, you need to log in
It's not entirely clear what you want. Or rather, what you want is clear, it is not clear why.
If you want to delegate absolutely all methods to the IR instance - then why don't you just return the IR instance through the I interface from object A - why should A itself implement I?
If mediation A is still necessary, it means that you want to give it some kind of semantic load. Those. if you want A to implement I itself, then you want it to hide the fact that the calls are actually delegated to the IR instance.
Since you want the fact of delegation to be hidden from the client of class A, then probably, over time, you will want to change the delegation logic, and delegate, for example, not to IR, but to another implementation of the interface I (otherwise, why would you need such a hiding of the fact of delegation to IR ). And if so, then it is quite logical that you should explicitly implement methods that delegate themselves to IR methods.
Why am I doing all this? Of course, one can imagine that the delegation code is automatically generated based on a construct like yours (implements I by delegate), however: there will be no clear answer; b) I think this is possible in languages with powerful macros, but the only ones that come to my mind are ones that you are unlikely to use, such as Nemerle or Lisp. And, well, this can be done on the C ++ preprocessor.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question