php适配器模式
Posted wgchen~
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php适配器模式相关的知识,希望对你有一定的参考价值。
阅读目录
场景
应用 adapter 目录
test.php
<?php
/**
* 结构型模式
*
* php适配器模式
* 把实现了不同接口的对象通过适配器的方式组合起来放在一个新的环境
*
* @author willem <https://wgchen.blog.csdn.net>
* @example 运行 php test.php
*/
// 注册自加载
spl_autoload_register('autoload');
function autoload($class)
require dirname($_SERVER['SCRIPT_FILENAME']) . '//..//' . str_replace('\\\\', '/', $class) . '.php';
/************************************* test *************************************/
use adapter\\AudioPlayer;
try
//生产一台设备
$mp4 = new AudioPlayer();
// 播放一个mp3
$mp4->play('忍者', 'mp3');
// 播放一个wma
$mp4->play('彩虹', 'wma');
// 播放一个mp4
$mp4->play('龙卷风mv', 'mp4');
catch (\\Exception $e)
echo $e->getMessage();
playing file:忍者.mp3
AdvanceWmaPlayer driver playing file: 彩虹.wma
AdvanceMp4Player driver playing file: 龙卷风.mp4
AudioPlayer.php
<?php
namespace adapter;
use Exception;
/**
* 音频设备实体
*/
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;
MediaInterface.php
<?php
namespace adapter;
/**
* 普通媒体接口
*/
interface MediaInterface
public function play($file='');
Adapter.php
<?php
namespace adapter;
use Exception;
/**
* 高级播放器适配器
*/
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;
AdvanceMp4Player.php
<?php
namespace adapter;
/**
* mp4高级播放器实体
*/
class AdvanceMp4Player implements MediaAdvanceInterface
public function playMp4($file='')
echo 'AdvanceMp4Player driver playing file: ' . $file . ".mp4\\n";
public function playWma($file='')
//do nothing
MediaAdvanceInterface.php
<?php
namespace adapter;
/**
* 高级媒体接口
*/
interface MediaAdvanceInterface
public function playMp4($file='');
public function playWma($file='');
AdvanceWmaPlayer.php
<?php
namespace adapter;
/**
* wma高级播放器实体
*/
class AdvanceWmaPlayer implements MediaAdvanceInterface
public function playMp4($file='')
//do nothing
public function playWma($file='')
echo 'AdvanceWmaPlayer driver playing file: ' . $file . ".wma\\n";
以上是关于php适配器模式的主要内容,如果未能解决你的问题,请参考以下文章