适配器模式

我们日常的业务中,总会遇到保留原有的接口调用还要兼容其他外来的接口,有时外来的接口实现方式还与原有的接口不一样。

这个时候最直接的想法就是重新写个类库或者在原有的类上新增方法,这样一次两次还好,次数多了,工作量不说,类库会越来越庞大造成系统崩溃就不好了。

此时,适配器就可以用到了。

eg.

<?php 

/**
 * 原有类方法
 * 定义抽象类,其中只有开和关
 */
abstract class Toy{
    public abstract function openMouth();

    public abstract function closeMouth();
}
?>
<?php 

/**
 * 原有类方法
 * 普通类,定义具体实现
 */
require_once('Toy.php');
class Dog extends Toy{
    public function openMouth(){
        echo 'Dog open Mouth<br>';
    }

    public function closeMouth(){
        echo 'Dog close Mouth<br>';
    }
}

class Cat extends Toy{
    public function openMouth(){
        echo 'Cat open Mouth<br>';
    }

    public function closeMouth(){
        echo 'Cat close Mouth<br>';
    }
}
?>

外来业务:

<?php 

/**
 * 接口,定义外来业务函数
 */
//外来业务1
interface RedTarget{
    public function doMouthOpen();
    public function doMouthClose();
}

//外来业务2
interface GreenTarget{
    public function operateMouth($type = 0);
}
?>
<?php 

/**
 * 普类,业务1的具体实现
 */
require_once('Toy.php');
require_once('Target_api.php');
class RedAdapter implements RedTarget{
    private $adaptee;
    function __construct(Toy $adaptee){
        $this->adaptee = $adaptee;
    }

    public function doMouthOpen(){
        $this->adaptee->openMouth();
    }

    public function doMouthClose(){
        $this->adaptee->closeMouth();
    }
}


class GreenAdapter implements GreenTarget{
    private $adaptee;
    function __construct(Toy $adaptee){
        $this->adaptee = $adaptee;
    }

    public function operateMouth($type = 0){
        if($type){
            $this->adaptee->openMouth();
        }else{
            $this->adaptee->closeMouth();
        }
    }
}
?>

执行代码:

<?php 

/**
 * 执行代码
 */
require_once('Dog.php');
require_once('Adapter.php');
class testDriver{
    public function run(){
        //实例化原有业务
        $adaptee_dog = new Dog();
        echo '给狗套上红枣适配器<br>';
        $adapter_red = new RedAdapter($adaptee_dog);
        //张嘴
        $adapter_red->doMouthOpen();
        //闭嘴
        $adapter_red->doMouthClose();
        echo '给狗套上绿枣适配器<br>';
        $adapter_green = new GreenAdapter($adaptee_dog);
        //张嘴
        $adapter_green->operateMouth(1);
        //闭嘴
        $adapter_green->operateMouth(0);
    }
}

$test = new testDriver();
$test->run();

?>

推荐两篇博文,很不错

 https://www.cnblogs.com/DeanChopper/p/4770572.html

 http://www.cnblogs.com/whoknows/articles/adapter_in_php.html

posted @ 2019-03-26 17:00  谦逊的铅笔  阅读(160)  评论(0编辑  收藏  举报