design-patternsadapterclass-designooad

Adapter Design Pattern with one Adaptee class inheriting the other?


I've recently came across this question and I'm just curious if my answer is correct, and if not, where I made a mistake.

My Task:

The signatures of classes A and B are incompatible. Class C is to connect A and B with the Design Pattern Adapter.

What are the advantages of having C inherit from A and B? Explain whether it would make sense to have B inherit from A and C inherit from B.

My answer:

The advantage of making C inherit from A and B is that the signature conflict can be resolved, while A and B could still be instantiated separately.

It would not make sense to have B inherit from A and C inherit from B, because if the functionality that previously caused the conflict is inherited from A to C, B has to take over the implementation of A, the functionality of B would be changed, this would not be the purpose of the design pattern adapter.

Thanks :-)


Solution

  • The Adapter Pattern (like all other GoF design patterns) has a well documented structure. There are two ways to implement this pattern :

    1. Object adapter : The Adapter class wraps the Adaptee.
    2. Class adapter : The Adapter class inherits from the Adaptee.

    With this in mind, let us look at the key part of the question being asked :

    Explain whether it would make sense to have B inherit from A and C inherit from B.

    It would not make sense to do this for the following reasons :

    1. If one is looking to implement the adapter pattern, this cannot be called the Adapter Pattern per-se (as C is neither an Object Aadapter nor a Class Adapter)
    2. Adapter pattern or not, it violates the IS-A relationship. Assume that class A is Android and class B is Blackberry. If B inherits A, it violates the IS-A relationship because Android is not a Blackberry.

    Point 2. above is exactly why we need the Adapter pattern. We create a BlackberryToAndroidAdapter class that inherits from Android and Blackberry This is nothing but an example of the Class Adapter pattern and in the context of this question, this is the class C.