我正在尝试学习GoF设计模式。到目前为止,我了解Singleton,Facade和Strategy。但是我对适配器模式感到困惑/困惑。这是我尝试在PHP中实现模式的方法: [摘要:Rhythmbox是音乐播放器,VLC是视频播放器。但是我想在VLC中播放音乐]
if fetchedArray.map{$0.patientID}.contains(newID) {
// show alert here as id exists
return
}
// proceed in saving the new record
但是我认为我没有正确实现它。要么我无法理解它的重要性。当我完成适配器的编写后,我想到了什么:为什么有人不直接使用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?
来播放Rhythmbox
而使用Music
呢?在什么时候或什么情况下应该选择VLCAdapter
?
有人可以解释一下如何从中受益吗?或者,我不明白什么?