0

I am trying to learn the GoF design patterns. So far, I understand Singleton, Facade and Strategy. But I am stuck/confused with the adapter pattern. Here is how I tried to implement the pattern in PHP: [Summary: Rhythmbox is a music player, VLC is a video player. But I want to play music in VLC]

interface Listenable {
    public function playMusic();
}

interface Watchable {
    public function watchVideo();
}

class Music implements Listenable {
    public function playMusic() {
        echo 'Playing a music';   
    }
}

class Video implements Watchable {
    public function watchVideo() {
        echo 'Playing a video';   
    }
}

class Rhythmbox {
    public function play($music) {
        $music->playMusic();
    }
}

class VLC {
    public function watch($video) {
        $video->watchVideo();
    }
}

class VLCAdapter implements Watchable {
    public $music;

    public function __construct($music) {
        $this->music = $music;
    }
    public function watchVideo() {
        $this->music->playMusic();   
    }
}

(new VLCAdapter(new Music))->watchVideo(); # Why this?
(new Rhythmbox)->play(new Music); # Why not this?

But I think I didn't implement it properly. Either that or I am unable to comprehend it's significance. As I finished writing the adapter, something occurred to me: why would someone not use Rhythmbox directly to play the Music and use VLCAdapter instead?. At what point or under what circumstances should one opt for the VLCAdapter?

Can someone please explain how can one benefit from it? Or, what am I not understanding?

Tanmay
  • 3,009
  • 9
  • 53
  • 83
  • `Adapter` used when some object should be treated as another object, similar to others. To use `adapter` there should be objects of same interface and one object which __does not__ support this interface. – u_mulder Sep 08 '18 at 19:31
  • @u_mulder could you provide an example based on my vlc-rythmbox analogy? – Tanmay Sep 09 '18 at 04:21
  • > one object which does not support this interface. Yes `new Music` object doesn't support the `Watchable` interface – Tanmay Sep 09 '18 at 04:55

1 Answers1

0

The part that is wrong is when you play the music. You need to use the VLC player so you can't do this:

(new VLCAdapter(new Music))->watchVideo();

Instead you need to do this:

$player = new VCL();
$player->watch(new VLCAdapter(new Music));

The whole point of using an adapter is you want to use your interface with an incompatible interface, so yes of course you can use the Rhythmbox directly, but the spec is asking that you use VCL player to play the music so you are not allowed to do:

(new Rhythmbox)->play(new Music); 

If you are interested I gave another real world example of adapter here: https://stackoverflow.com/a/73166510/8485567.

Bernard Wiesner
  • 961
  • 6
  • 14