dongping9475 2018-09-08 19:14
浏览 30

在PHP中实现和理解适配器模式

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?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 基于双目测规则物体尺寸
    • ¥15 wegame打不开英雄联盟
    • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
    • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
    • ¥30 eclipse开启服务后,网页无法打开
    • ¥30 雷达辐射源信号参考模型
    • ¥15 html+css+js如何实现这样子的效果?
    • ¥15 STM32单片机自主设计
    • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
    • ¥15 不小心不正规的开发公司导致不给我们y码,