Jordi Adell
Jordi Adell

Reputation: 91

What is the best way to implement the adaptor pattern in c++

I have seen that it is possible to use inheritance, such as:

class A {
};

class Legacy{
};

class B : public A, private Legacy {
};

But it is weird to me to inherit public and private from two different classes. Is there an alternative way to implement the adapter pattern?

Upvotes: 0

Views: 897

Answers (2)

Kedar Tokekar
Kedar Tokekar

Reputation: 418

Here you are using class Adapter. Using Adapter itself is a compromise (we use Adapter when we do not have control over the Legacy Adaptee but still want to use it). For specific purpose (matching the required and provided interfaces) we force Adapter to inherit from Adaptee as well as Target. As such Adapter class (suffering from multiple inheritance) is not reusable domain class across application, its just a (AKA) wrapper class. Its "IsA" relationship with Adaptee as well as Target is forceful and not naturally coming from domain model.

Even then as pointed out by @dlasalle, using Object Adapter by composition will make its use more safe. But the choice depends upon trade off between both types. e.g. if 80% of functionality of Adapter is being published by Adapter as it is, then Class adapter is a good choice to avoid writing wrapper methods for all those 80%. C++ implementation has choice of using class adapter (with due care) which Java does not have.

Upvotes: 0

dlasalle
dlasalle

Reputation: 1725

Generally it is better to use composition instead of inheritance for adapters (and many other cases too):

class B : public A {
  public:
    /* implementation of abstract methods of A with calls to Legacy */

  private:
    Legacy m_leg;
};

Upvotes: 3

Related Questions