Pattern for using two implementations of one class if no common interface available

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?

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow