alianos-
alianos-

Reputation: 916

How can I create implementations of interfaces, that are use specific implementations of other interfaces?

I definitely could not explain what I mean in the title. The issue is either too stupid or too complicated, but the bottom end is that I could not find an appropriate design pattern for it.

So to the point, lets assume that we have class A which contains a reference to interface B. A computational procedure determines which implementation of B is appropriate and instantiates a new object. So far so good (I think).

Now B has a method that is based on a set of parameters. Object A holds a set of default parameters but any set may be given on demand. The tricky part is that parameters are completely different among implementations of interface B. In truth these parameters are different objects themselves with their own methods, which are different per implementation of B.

My initial approach was to create an interface C for the parameters, and then create one implementation of C for each implementation of B (its a one-to-one relation), but that did not seem right. If not anything else, in each unique implementation of B, I had to cast C to the respective implementation needed to call its unique functions.

One can only assume there are prettier ways! Any ideas?

Upvotes: 1

Views: 95

Answers (2)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272507

As has been pointed out in other answers, B is not a proper interface (in the moral sense). If these params really can't be made part of each B implementation, then you could still achieve a proper interface by abstracting the details away:

interface BWrapper {
    public void doSomething();
}

class ConcreteB {
    public static class Params { ... }

    public class Wrapper implements BWrapper() {
        public Wrapper(Params params) { this.params = params; }
        @Override
        public void doSomething()     { ConcreteB.doSomething(params); }
        private final Params params;
    }

    public void doSomething(Params params) { ... }
}


class A {
    void setWrapper(BWrapper wrapper) { this.wrapper = wrapper; }
    void foo()                        { wrapper.doSomething(); }

    private BWrapper wrapper;
}

...

A a = new A();

ConcreteB.Params p1 = new ConcreteB.Params();
a.setWrapper(new ConcreteB.Wrapper(p1)); 
a.doSomething();

ConcreteB.Params p2 = new ConcreteB.Params();
a.setWrapper(new ConcreteB.Wrapper(p2)); 
a.doSomething();

Upvotes: 2

artbristol
artbristol

Reputation: 32407

B isn't a proper interface, if its users need to call its methods with particular parameters that depend on the underlying implementation. You should rethink your design. Why does A even have access to these parameters? Do they belong in each B implementation?

Upvotes: 5

Related Questions