1

Imagine we have some interface. We need to use two different implementations of this interface. The implementations exist. But there is a problem: the implementations do not formally implement that interface. Thats because they are in fact two independent products and they cannot be adjusted with our interfaces.

I.e.

interface Action {
void doAction();
}
class ActionFirstImpl {
void doAction() {
...
}
}
class ActionSecondImpl {
void doAction() {
...
}
}

What is the best way to use these implementations in our project? The only thing I can imagine is to create two intermediate classes which implement this interface and subclass this class from the implementations provided. Any other ideas?

asked Feb 19, 2014 at 15:07
0

2 Answers 2

4

I wouldn't subclass the implementation classes. I'd just use the adapter pattern and delegate to the implementation classes:

public final class ActionFirstImplAdapter implements Action {
 private final ActionFirstImpl delegate;
 public ActionFirstImplAdapter(ActionFirstImpl delegate) {
 this.delegate = delegate;
 }
 @Override
 public void doAction() {
 delegate.doAction();
 }
}

... and exactly the same for the ActionSecondImpl.

Normally the adapter pattern requires a bit more adaptation than just "delegate to a method with the exact same signature" but it still works in that simple case too.

answered Feb 19, 2014 at 15:10
Sign up to request clarification or add additional context in comments.

3 Comments

@nachokk: Added the @Override; not sure what you mean by "also saying that is object adapter version".
@nachokk: I reckon it's clear enough by the name - and the documentation can clarify further.
2

You can simply use delegation (i.e. the delegation pattern):

class ActionImplementingClass implements Action {
 private ActionFirstImpl data;
 // ...
 @Override
 public void doAction() {
 data.doAction();
 }
}

The same can be done with ActionSecondImpl.

answered Feb 19, 2014 at 15:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.