类适配
<?php
interface Target {
public function hello();
public function world();
}
class Adaptee {
public function greet() {
print_ln(__METHOD__);
}
public function world() {
print_ln(__METHOD__);
}
}
/**
* 对 target 接口 和 adaptee 具体实现进行适配
* 所有的适配细节对client透明
*/
class Adapter extends Adaptee implements Target {
public function hello() {
$this->greet();
}
}
class Client {
public static function main() {
//$o = new Target();
$o = new Adapter();
$o->hello();
$o->world();
}
}
Client::main();
对象适配
<?php
interface Target {
public function hello();
public function world();
}
class Adaptee {
public function greet() {
print_ln(__METHOD__);
}
public function world() {
print_ln(__METHOD__);
}
}
/**
* 通过包装Adaptee对象 对 target 接口 和 adaptee 具体实现适配
* client可随意选择合适的adaptee进行工作
* 必须要在Adapter中手动时间所有Target接口,具体工作由adaptee完成
*/
class Adapter implements Target {
private $_adaptee;
public function __construct(Adaptee $adaptee) {
$this->_adaptee = $adaptee;
}
public function hello() {
$this->_adaptee->greet();
}
public function world() {
$this->_adaptee->world();
}
}
class Client {
public static function main() {
$o = new Adapter(new Adaptee());
$o->hello();
$o->world();
}
}
Client::main();