PHP设计模式-配制器 发表于 2017-03-25 | 分类于 PHP | 评论数: | 阅读次数: 本文字数: 2.7k | 阅读时长 ≈ 2 分钟 适用性 把实现了不同接口的对象通过适配器的方式组合起来放在一个新的环境 代码示例123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135/** * 普通媒体接口 */interface MediaInterface{ public function play($file='');}/** * 高级媒体接口 */interface MediaAdvanceInterface{ public function playMp4($file=''); public function playWma($file='');}/** * 高级播放器适配器 */class Adapter{ private $_advancePlayerInstance; private $_type = ''; public function __construct($type='') { switch ($type) { case 'mp4': $this->_advancePlayerInstance = new AdvanceMp4Player(); break; case 'wma': $this->_advancePlayerInstance = new AdvanceWmaPlayer(); break; default: throw new Exception("$type is not supported", 400); break; } $this->_type = $type; } public function play($file='') { switch ($this->_type) { case 'mp4': $this->_advancePlayerInstance->playMp4($file); break; case 'wma': $this->_advancePlayerInstance->playWma($file); break; default: break; } }}/** * mp4高级播放器实体 */class AdvanceMp4Player implements MediaAdvanceInterface{ public function playMp4($file='') { echo 'AdvanceMp4Player driver playing file: ' . $file . ".mp4\n"; } public function playWma($file='') { //do nothing }}/** * wma高级播放器实体 */class AdvanceWmaPlayer implements MediaAdvanceInterface{ public function playMp4($file='') { //do nothing } public function playWma($file='') { echo 'AdvanceWmaPlayer driver playing file: ' . $file . ".wma\n"; }}/** * 音频设备实体 */class AudioPlayer implements MediaInterface{ public function play($file='', $type='') { switch ($type) { case 'mp3': echo 'playing file: ' . $file . ".mp3\n"; break; case 'mp4': $adapter = new Adapter($type); $adapter->play($file); break; case 'wma': $adapter = new Adapter($type); $adapter->play($file); break; default: throw new Exception("$type is not supported", 400); break; } }}try { //生产一台设备 $mp4 = new AudioPlayer(); // 播放一个mp3 $mp4->play('忍者', 'mp3'); // 播放一个wma $mp4->play('彩虹', 'wma'); // 播放一个mp4 $mp4->play('龙卷风mv', 'mp4');} catch (\Exception $e) { echo $e->getMessage();}