适配器模式(Adapter)
介绍
结构型模式,提取多个不兼容类的相近方法构建接口,建立适配类实现接口。增减实现类的时候,不用修改调用端与适配器的交互代码,减少了代码间的耦合性。
何时使用:现有类和新增的类相关性不大,需要用到部分相关代码的时候。
优点:
- 让多个没有关联的类一起运行;
- 提高类的复用;
- 增加类的透明度;
- 灵活定较好。
缺点:
过度的使用适配器,会让系统非常零乱。
代码实现
<?php
interface Animal{
function getName();
function call();
}
class Cat{
function getName(){
echo 'I\m a cat;';
}
function call(){
echo 'miao~~';
}
function other1(){
echo 'other1';
}
}
class Dog{
function getName(){
echo 'I\m a dog;';
}
function call(){
echo 'wang!';
}
function other2(){
echo 'other2';
}
}
class Adapter implements Animal{
private $animal;
function __construct($animal){
$this->animal = $animal;
}
function getName(){
$this->animal->getName();
}
function call(){
$this->animal->call();
}
}
$adapter = new Adapter(new Cat);
$adapter->call();