PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 26, 2022

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

 October 26, 2022     design-patterns, java, oop     No comments   

Issue

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


Solution

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.



Answered By - StepUp
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing