Search code examples
c++design-patternsadapter

Is this an adapter design pattern correctly implemented? If not what am I missing?


I made an effort to create an adapter design pattern. A simple interface using which users can connect to both old and modern media player.

The modern media player plays mp4 format, whereas the old plays only wav format. Using the class mediaPlayerInterface users can play both media types.

If you feel this is not an adapter design pattern, please comment what is missing. How can I modify it to Adapter pattern? I am a little new to design patterns.

#include <iostream>
#include <string>

using namespace std;

class MediaPlayer
{
   public:
      virtual void playSong()=0;
};

class ModernMediaPlayer : public MediaPlayer
{
   public:
    void playSong( )
    {
        cout << "Playing from modern media player" << endl;
    }

};

class oldMediaPlayer: public MediaPlayer
{
   public:
    void playSong( )
    {
        cout << "Playing from old media player" << endl;
    }
};

class mediaPlayerInterface
{
   private:
       string fileType;

   public:
        mediaPlayerInterface(string fType)
        {
          fileType=fType;
        }

        MediaPlayer* getMediaPlayer( )
        {
             if (fileType == "mp4")
             {
                 return new ModernMediaPlayer;
             }
             else if (fileType == "wav")
             {
                 return new oldMediaPlayer;
             }
        }
};

int main()
{
   mediaPlayerInterface *mIface = new mediaPlayerInterface("mp4");
   MediaPlayer *mplayer = mIface->getMediaPlayer();

   mplayer->playSong();

   mIface = new mediaPlayerInterface("wav");
   mplayer = mIface->getMediaPlayer();

  mplayer->playSong();
}


Output:
Playing from modern media player
Playing from old media player

Solution

  • Below is an example of the adapter pattern. What's essential is that the AscSequenceControl has all required functionality, but it can not be connected to the MovementPlanner, since the interface isn't compatible. So the RouteSegmenter indeed "adapts" this. It has the right interface and its implementation just uses the AscSequenceControl.

    enter image description here

    So in your example: You have a MediaPlayer with a method: gotoTrack (int trackNr). But the class MediaPlayerUser wants to say: mediaPlayer.nextTrack () and mediaPlayer.previousTrack (). So you make a bridge class MediaPlayerBridge. It has an attribute mediaPlayer and method nextTrack that calls mediaPlayer.gotoTrack (++currentTrack) and a method previousTrack that calls mediaPlayer.gotoTrack (--currentTrack).

    enter image description here