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?