Adapter Design Pattern Explained

By | August 22, 2015

In this tutorial we will implement Adapter design pattern using c++. And I will use the much denounced multiple inheritance in c++ too.
Adapter design pattern is one of the easier design patterns. As usual, we will first discuss the “WHY” and then the “HOW”.

In one word : Legacy.
Adapter design pattern is the answer to the question “So what do you do with good ol’ boys like me?“.
It allows you to use the old(read already implemented and working) software which is doing something similar to what you want. Just that the times (read interfaces) changed.

It is very simple. Get hold of the snazzy new interface which the client wants to use. Implement the interface via the Adapter class. Take the legacy class. Call the legacy class methods inside the adapter class methods.

Time for some code.

Let us suppose we have an old player which plays songs. It has a method called OldPlay which takes the volume at which the song has to be played as a parameter. The new interface which we have has a play method too. But that method does not take the volume as a parameter. So lets put Adapter design pattern in action.

  • Line 07: The wicked new interface everyone wants to use.
  • Line 10: The Play method does not need anything.
  • Line 13: The good old class which was fine in times before.
  • Line 17: The OldPlayer class cTor wants the song name.
  • Line 19: The OldPlay method which actually wants what volume to play the song at.
  • Line 25: The adapter class doing the unthinkable. Multiple inheritance.
  • Line 29: The cTor of this class takes in the volume as well as the song to be played. Passes the song name to the cTor of the OldPlayer class. And stores the volume at which the song will be played.
  • Line 31: The Play method. See the cheeky thing happening in that method. The OldPlay method gets called with the volume parameter.
  • Line 39: The hot new player for new generation. See that the song name as well as the volume at which it has to be played is passed on.
  • Line 40: And the Play method which is not taking anything. And the new generation is happy. Whatever man.

And this is the output:

Adapter Pattern Demo

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.