适配器模式(Adapter):可以将截然不同的函数和接口封装成统一的api
Adapter模式使得原来由于接口不兼容而不能一起工作的那此类可以一起工作
实际应用举例:php的数据库操作有mysql,mysqli,pdo 三种,当这三种的操作方法不是相同的,我们可以使用适配器模式将其操作方式统一成一致的。
类似的场景还有cache适配器,将memcache,redis,file,apc等不同的缓存函数统一成一致的函数
<?php
// 目标角色
interface Target {
// 源类也有的方法1
public function sampleMethod1();
// 源类没有的方法2
public function sampleMethod2();
}
// 源角色
class Adaptee {
// 源类含有的方法
public function sampleMethod1() {
echo 'Adaptee sampleMethod1 <br />';
}
}
// 类适配器角色
class Adapter implements Target {
private $_adaptee;
public function __construct($adaptee) {
$this->_adaptee = $adaptee;
}
// 委派调用Adaptee的sampleMethod1方法
public function sampleMethod1() {
$this->_adaptee->sampleMethod1();
}
// 源类中没有sampleMethod2方法,在此补充
public function sampleMethod2() {
echo 'Adapter sampleMethod2 <br />';
}
}
class Client {
public static function main() {
$adapter = new Adapter(new Adaptee());
$adapter->sampleMethod1();//原方法
$adapter->sampleMethod2();//适配方法
}
}
$test = new Client();
$test->main();