KutaBeach
KutaBeach

Reputation: 1495

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?

Upvotes: 1

Views: 690

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500675

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.

Upvotes: 4

arshajii
arshajii

Reputation: 129507

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.

Upvotes: 2

Related Questions