PHP – 适配器模式

一、概述

  将一个类的接口转换成客户希望的另一个接口,适配器模式使得原本的由于接口不兼容而不能一起工作的那些类可以一起工作。

  应用场景:老代码接口不适应新的接口需求,或者代码很多很乱不便于继续修改,或者使用第三方类库。

 

二、PHP 代码

<?php
declare(strict_types = 1);

/**
 * 目标类接口
 * Interface Target 我们期望得到的功能类
 * @package Extend
 */
interface Target
{
    public function simpleMethod1();
    public function simpleMethod2();
}


/**
 * 原始类(在新功能提出之前的旧功能类和方法)
 *
 * Class OriginClass
 */
class OriginClass
{

    public function simpleMethod1()
    {
        return 'OriginClass simpleMethod1'."<br>";
    }

}

/**
 * 类适配器(新定义接口的具体实现)
 * Class Adapter
 * @package Extend
 */
class Adapter implements Target
{

    private $origin;

    function __construct()
    {
        //适配器初始化直接new 原功能类,以方便之后委派
        $this->origin = new OriginClass();
    }

    public function simpleMethod1()
    {
        return $this->origin->simpleMethod1();
    }

    public function simpleMethod2()
    {
        return 'Adapter simpleMethod2'."<br>";
    }
}


$adapter = new Adapter();
echo $adapter->simpleMethod1();
echo $adapter->simpleMethod2();