类适配器使用的是继承:
<?php
/**
* 类适配器模式
* @author guisu
*
*/
/**
* 目标角色
* @version 2.0
*/
interface Target {
/**
* 源类的方法:这个方法将来有可能继续改进
*/
public function hello();
/**
* 目标点
*/
public function world();
}
/**
* 源角色:被适配的角色
*/
class Adaptee {
/**
* 源类含有的方法
*/
public function world() {
echo ' world <br />';
}
/**
* 加入新的方法
*/
public function greet() {
echo ' Greet ';
}
}
/**
* 类适配器角色
*/
class Adapter extends Adaptee implements Target {
/**
* 源类中没有world方法,在此补充
*/
public function hello() {
parent::greet();
}
}
/**
* 客户端程序
*
*/
class Client {
/**
* Main program.
*/
public static function main() {
$adapter = new Adapter();
$adapter->hello();
$adapter->world();
}
}
Client::main();
?>
对象适配器使用的是委派
<?php
/**
* 类适配器模式
* @author guisu
*
*/
/**
* 目标角色
* @version 2.0
*/
interface Target {
/**
* 源类的方法:这个方法将来有可能继续改进
*/
public function hello();
/**
* 目标点
*/
public function world();
}
/**
* 源角色:被适配的角色
*/
class Adaptee {
/**
* 源类含有的方法
*/
public function world() {
echo ' world <br />';
}
/**
* 加入新的方法
*/
public function greet() {
echo ' Greet ';
}
}
/**
* 类适配器角色
*/
class Adapter implements Target {
private $_adaptee;
/**
* construct
*
* @param Adaptee $adaptee
*/
public function __construct(Adaptee $adaptee) {
$this->_adaptee = $adaptee;
}
/**
* 源类中没有world方法,在此补充
*/
public function hello() {
$this->_adaptee->greet();
}
/**
* 源类中没有world方法,在此补充
*/
public function world() {
$this->_adaptee->world();
}
}
/**
* 客户端程序
*
*/
class Client {
/**
* Main program.
*/
public static function main() {
$adaptee = new Adaptee();
$adapter = new Adapter($adaptee);
$adapter->hello();
$adapter->world();
}
}
Client::main();
?>
如例中代码所示,你可以运用适配器(Adapter)模式来避免因外部库改变所带来的不便——倘若向上兼容。作为某个库的开发者,你应该独立编写适配器,使你的用户更简便地使用新版本的库,而不用去修改他们现有的全部代码。
GoF书中提出的适配器(Adapter)模式更倾向于运用继承而不是组成。这在强类型语言中是有利的,因为适配器(Adapter)事实上是一个目标类的子类,因而能更好地与类中方法相结合。
