Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 515
Omri Grinshpan Avatar asked Oct 20 '25 14:10

Omri Grinshpan


2 Answers

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.

like image 58
jaco0646 Avatar answered Oct 23 '25 04:10

jaco0646


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.

like image 23
StepUp Avatar answered Oct 23 '25 03:10

StepUp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!