PHP 适配器模式

适配器模式(Adapter)模式:将一个类的接口,转换成客户期望的另一个类的接口。适配器让原本接口不兼容的类可以合作无间。
 
 
【适配器模式中主要角色】
目标(Target)角色:定义客户端使用的与特定领域相关的接口,这也就是我们所期待得到的
源(Adaptee)角色:需要进行适配的接口
适配器(Adapter)角色:对Adaptee的接口与Target接口进行适配;适配器是本模式的核心,适配器把源接口转换成目标接口,此角色为具体类。
 
其实也就是你家墙上有一个两口的插座(Adaptee),但你买了一个电风扇(Target)需要三个口的,这个时候你就需要一个插排(Adapter)。

 

【类适配器模式PHP示例】
类适配器使用的是继承
/**
 * 目标角色
 */
interface Target {

    /**
     * 源类也有的方法1
     */
    public function sampleMethod1();

    /**
     * 源类没有的方法2
     */
    public function sampleMethod2();
}

/**
 * 源角色
 */
class Adaptee {

    /**
     * 源类含有的方法
     */
    public function sampleMethod1() {
        echo 'Adaptee sampleMethod1 <br />';
    }
}

/**
 * 类适配器角色
 */
class Adapter extends Adaptee implements Target {

    /**
     * 源类中没有sampleMethod2方法,在此补充
     */
    public function sampleMethod2() {
        echo 'Adapter sampleMethod2 <br />';
    }

}

class Client {

    /**
     * Main program.
     */
    public static function main() {
        $adapter = new Adapter();
        $adapter->sampleMethod1();
        $adapter->sampleMethod2();

    }

}

  

【对象适配器模式PHP示例】
对象适配器使用的是委派

/**
 * 目标角色
 */
interface Target {

    /**
     * 源类也有的方法1
     */
    public function sampleMethod1();

    /**
     * 源类没有的方法2
     */
    public function sampleMethod2();
}

/**
 * 源角色
 */
class Adaptee {

    /**
     * 源类含有的方法
     */
    public function sampleMethod1() {
        echo 'Adaptee sampleMethod1 <br />';
    }
}

/**
 * 类适配器角色
 */
class Adapter implements Target {

    private $_adaptee;

    public function __construct(Adaptee $adaptee) {
        $this->_adaptee = $adaptee;
    }

    /**
     * 委派调用Adaptee的sampleMethod1方法
     */
    public function sampleMethod1() {
        $this->_adaptee->sampleMethod1();
    }

    /**
     * 源类中没有sampleMethod2方法,在此补充
     */
    public function sampleMethod2() {
        echo 'Adapter sampleMethod2 <br />';
    }

}

class Client {

    /**
     * Main program.
     */
    public static function main() {
        $adaptee = new Adaptee();
        $adapter = new Adapter($adaptee);
        $adapter->sampleMethod1();
        $adapter->sampleMethod2();

    }

}

  类适配器采用“多继承”的实现方式,带来了不良的高耦合,所以一般不推荐使用。对象适配器采用“对象组合”的方式,更符合松耦合精神。

这里还有一篇对对象适配器的很好的说明可以看一下http://www.knowsky.com/890188.html。

posted on 2016-12-28 16:39  莫小安  阅读(4895)  评论(1编辑  收藏  举报

导航