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)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.