设计模式php实例:适配器模式

适配器模式将一个类的换成客户端需要的另一个接口,使原本不兼容的接口能一起工作。一个现实中的例子,假如屋里墙上只有两项插口,而风扇有三个插头,这时需要再拿一个移动插线板,插线板接入墙壁插口的一段是两项插头,插线板另外一段能够提供三项插口给风扇,这时候插线板起到了一个适配器的作用。

在应用中,适配器模式分为类适配器和对象适配器。


类适配器


类适配器中适配器继承原有的Adaptee类,自己实现原类没有的操作。

interface ITarget
{
    function operation1();
    function operation2();
}

interface IAdaptee
{
    function operation1();
}

class Adaptee extends IAdaptee
{
    public  function operation1()
    {
        echo "原方法";
    }
}

class Adapter extends Adaptee implements IAdaptee, ITarget
{
    public  function operation2()
    {
        echo "适配方法";
    }
}

class Client
{
    public  function test()
    {
        $adapter = new Adapter();
        $adapter->operation1();//原方法
        $adapter->operation2();//适配方法
    }
}


对象配器


类适配器使用的是继承模式,而对象适配器使用的是组合模式,将adaptee作为adapter的一个引用。

interface ITarget
{
    function operation1();
    function operation2();
}

interface IAdaptee
{
    function operation1();
}

class Adaptee extends IAdaptee
{
    public  function operation1()
    {
        echo "原方法";
    }
}

class Adapter implements  ITarget
{
    private $adaptee;

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

    public  function operation1()
    {
         return $this->adaptee->operation1();
    }

    public  function operation2()
    {
        echo "适配方法";
    }
}


class Client
{
    public  function test()
    {
        $adapter = new Adapter(new Adaptee(null));
        $adapter->operation1();//原方法
        $adapter->operation2();//适配方法
    }
}
由于组合在耦合性上小于继承,对象适配器显得更加灵活,当然它的缺点是增加代码量。 需要重写adapee中的方法的数量太大的话,可以考虑在adapter中使用__call方法委托adapee取得客户端调用的方法
    public function __call($func, $args)
    {
        if (is_callable(array($this->adaptee, $func))) {
            return $this->adaptee->$func($args);
        }
        trigger_error('*********', E_USER_ERROR);
    }



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值