Home > Enterprise >  Why the Class Adapter Design Pattern Can't Use an Interface Instead of Multiple Inheritance?
Why the Class Adapter Design Pattern Can't Use an Interface Instead of Multiple Inheritance?

Time:09-18

I've recently learned the Class Adapter pattern. In order to implement it, the language used must support multiple inheritance since the adapter class must inherit two classes, the Target, and the Adaptee. So in a language like Java, it could not be done.

But why couldn't it use an interface Target instead of a class Target? More inline with the Object Adapter pattern as well. Just switching from object composition (Adapter having the Adaptee) to single inheritance (Adapter inheriting the Adaptee). By using an interface, I don't see the design difference, and as a result, the pattern can be used in Java.

Link to object adapter and class adapter class diagram

CodePudding user response:

But why couldn't it use an interface Target instead of a class Target?

you can use interface. But then you will have duplication of code, but multiple inheritance removes duplication of code.

Let me show an example.

Our abstractions:

public interface IDuck
{
    void Quack();
}

public interface ITurkey
{
    void Gobble();
}

And concrete implementations:

public class Duck : IDuck
{
    public void Quack()
    {
        Console.WriteLine("Quack");
    }
}

public class Turkey : ITurkey
{
    public void Gobble()
    {
        Console.WriteLine("Gobble");
    }
}

And class adapter would look like this:

public class ClassAdapter : IDuck, ITurkey
{
    public void Gobble()
    {
        // duplication of code
        Console.WriteLine("Gobble");
    }

    public void Quack()
    {
        Gobble();
    }
}

The above ClassAdapter has duplications of code. Sure we can extract this code and provide it through composition or inject Duck and Turkey. However, it brings additional dependencies and some complexity. So it is better to use object adapter pattern. Your code will be simpler. Simple code is almost always the best choice.

CodePudding user response:

There's generally no reason you can't create a Class Adapter between two interfaces in Java. But first you have to be lucky enough to be in a scenario where the two APIs that need adapting are both interfaces to begin with.

An Adapter is mostly useful to bridge the gap between two existing APIs that don't belong to you. If you control one or both APIs, you can simply change one to match the other. When you need two separate APIs to be compatible, but the APIs don't belong to you, then you have to adapt what you're given, which may not be interfaces.

  • Related