设计模式-适配器模式

设计模式-策略模式

说明

适配器模式(Adapter Pattern):将某个对象的接口适配为另一个对象所期望的接口。属于结构型设计模式。


模式说明

【适配器模式中主要角色】
目标(Target)角色:定义客户端使用的与特定领域相关的接口,这也就是我们所期待得到的
源(Adaptee)角色:需要进行适配的接口
适配器(Adapter)角色:对Adaptee的接口与Target接口进行适配;适配器是本模式的核心,适配器把源接口转换成目标接口,此角色为具体类。

说明示例:就类似于生活中你家墙上有一个两口的插座(Adaptee),但你买了一个电风扇(Target)需要三个口的,这个时候你就需要一个插排(Adapter)。

类适配器

/**
 * 适配器模式(Adapter Pattern):将某个对象的接口适配为另一个对象所期望的接口。属于结构型设计模式。
 */
//例子:生活中你家墙上有一个两口的插座(Adaptee),但你买了一个电风扇(Target)需要三个口的,这个时候你就需要一个插排(Adapter)。
//目标(Target)角色:定义客户端使用的与特定领域相关的接口,
//源(Adaptee)角色:需要进行适配的接口 墙上两口插座
//适配器(Adapter)角色:对Adaptee的接口与Target接口进行适配;适配器是本模式的核心,适配器把源接口转换成目标接口,此角色为具体类。 连接两口插座,提供三口充电

/**
 * Class Adaptee
 * 源角色 (墙上插座,提供两口连电)
 */
class Adaptee {
    /**
     * 两口充电
     */
    public function twoCharge() {
        echo '两口连上有电';
    }
}


/**
 * Interface Target
 * 目标(Target)角色 
 * 风扇想要的接口 
 */
interface Target {

    /**
     * 两口连电 连接插座
     */
    public function twoCharge();

    /**
     * 三口连电 适配风扇
     */
    public function threeCharge();
}


/**
 * 适配器(Adapter)角色 (插排)
 * 连接墙上插座,提供三口充电
 */
class Adapter extends Adaptee implements Target {
    
    public function threeCharge() {
        echo '支持三口连接';
    }

}

class Client {
    
    public static function main() {
        $adapter = new Adapter();
        $adapter->twoCharge();
        $adapter->threeCharge();
    }
}

$fan= new Client();
$fan->main();

对象适配器模式

<?php
/**
 * 适配器模式(Adapter Pattern):将某个对象的接口适配为另一个对象所期望的接口。属于结构型设计模式。
 */
//例子:生活中你家墙上有一个两口的插座(Adaptee),但你买了一个电风扇(Target)需要三个口的,这个时候你就需要一个插排(Adapter)。
//目标(Target)角色:定义客户端使用的与特定领域相关的接口,
//源(Adaptee)角色:需要进行适配的接口 墙上两口插座
//适配器(Adapter)角色:对Adaptee的接口与Target接口进行适配;适配器是本模式的核心,适配器把源接口转换成目标接口,此角色为具体类。 连接两口插座,提供三口充电

/**
 * Class Adaptee
 * 源角色 (墙上插座,提供两口连电)
 */
class Adaptee {
    /**
     * 两口充电
     */
    public function twoCharge() {
        echo '两口连上有电';
    }
}


/**
 * Interface Target
 * 目标(Target)角色
 * 风扇想要的接口
 */
interface Target {

    /**
     * 两口连电 连接插座
     */
    public function twoCharge();

    /**
     * 三口连电 适配风扇
     */
    public function threeCharge();
}


/**
 * 适配器(Adapter)角色 (插排)
 * 连接墙上插座,提供三口充电
 */
class Adapter implements Target {

    private $_adaptee;

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

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


    public function threeCharge() {
        echo '支持三口连接';
    }

}

class Client {
    /**
     * Main program.
     */
    public static function main() {
        $adaptee = new Adaptee();
        $adapter = new Adapter($adaptee);
        $adapter->twoCharge();
        $adapter->threeCharge();

    }

}

$fan= new Client();
$fan->main();

总结说明

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

结尾

心如花木,向阳而生。

添加新评论