//适配器模式
class Mp4
{
public function play($fileName)
{
echo 'play '.$fileName.'';
}
}
class Mp3
{
public function play($fileName)
{
echo 'play '.$fileName.'';
}
}
class MediaAdapter
{
public function play($audioType, $fileName)
{
$funcName='get_'.strtolower($audioType);
if (method_exists($this, $funcName))
{
$player = call_user_func(array($this,$funcName));
$player->play($fileName);
}else{
echo 'Invalid media.'.$audioType." format not supported";
}
}
private function get_mp4()
{
return new Mp4();
}
private function get_mp3()
{
return new Mp3();
}
}
class Vlc
{
public function play($fileName)
{
echo 'play '.$fileName.'';
}
}
class AudioPlayer extends MediaAdapter
{
protected function get_vlc()
{
return new Vlc();
}
}
$audioPlayer = new AudioPlayer();
$audioPlayer->play('Mp3','horizon.mp3');
$audioPlayer->play('Mp4','alone.mp4');
$audioPlayer->play('vlc','away.vlc');
$audioPlayer->play('avi','me.avi');
领取专属 10元无门槛券
私享最新 技术干货