P
P
protalk2016-06-24 13:54:23
OOP
protalk, 2016-06-24 13:54:23

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();
}

And here is its implementation:
public class IR implements I {

    @Override
    public int a() {
  return 1;
    }

    @Override
    public int b() {
  return 2;
    }

}

I would like to build a class that will also implement I and for this delegate all requests for I to the IR instance. You can do it with composition:
public class A implements I {
    IR delegat = new IR();

    @Override
    public int a() {
  return delegat.a();
    }

    @Override
    public int b() {
  return delegat.b();
    }

}

Not pretty. You can, of course, through inheritance:
public class B extends IR {

}

But this introduces its own limitations, for example, I cannot change the delegate in the course of life. Therefore, I want through the composition.
It is clear that Java cannot help here. Are there constructions in other languages ​​like:
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

1 answer(s)
S
Stanislav Makarov, 2016-06-24
@Nipheris

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 question

Ask a Question

731 491 924 answers to any question