php设计模式-适配器模式

适配器模式其实也是一种为了解耦的设计模式,为了让客户端的调用变得更简单统一,将源接口转换为目标接口的过程封装到特定的过程中,这个过程就叫适配。

逻辑图如下:

将特定的需要适配的类作为装饰器的一个成员变量进行注入,然后再暴露同一个调用接口。

具体代码如下:

<?php
/**
 * Created by PhpStorm.
 * User: tonny
 * Date: 2019/7/15
 * Time: 20:44
 */

interface Target
{
    public function charge();
}

class Adapter implements Target
{
    protected $adaptee = null;
    public function __construct($adaptee)
    {
        $this->adaptee = $adaptee;

    }

    public function charge()
    {
        $className = get_class($this->adaptee);
        if ($className == 'StreetEl') {
            $this->adaptee->shareCharge();
        } else if ($className == 'Battery') {
            $this->adaptee->selfCharge();
        }
    }
}

class StreetEl
{
    public function shareCharge()
    {
        echo "share way to charge it!
";
    }
}

class Battery
{
    public function selfCharge()
    {
        echo "self charging by battrey!
";
    }
}

$streeEl = new StreetEl();
$battery = new Battery();
$adapter = new Adapter($streeEl);
$adapter->charge();

这样代码的可扩展性和复用性能够很大的提高,也符合“开闭原则”。当然它也有坏处,可能会造成调用复杂,比如调用的是A,实际是调用的C

当然还有更符合php特色的写法,将需要适配的类的初始化也放到Adapter的构造函数里面,利用字符串变量来动态new对象。在这里只为了阐述通用型的适配器模式,就不展开说了。

原文地址:https://www.cnblogs.com/freephp/p/11191572.html