适配器

本文介绍了PHP中适配器模式的应用,包括类适配和对象适配两种方式,并提供了具体的代码实例。类适配通过继承的方式实现目标接口,而对象适配则通过组合的方式实现目标接口。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

类适配

<?php
interface Target {
    public function hello();

    public function world();
}

class Adaptee {
    public function greet() {
        print_ln(__METHOD__);
    }

    public function world() {
        print_ln(__METHOD__);
    }
}

/**
* 对 target 接口 和 adaptee 具体实现进行适配
* 所有的适配细节对client透明
*/
class Adapter extends Adaptee implements Target {
    public function hello() {
        $this->greet();
    }
}

class Client {
    public static function main() {
        //$o = new Target();
        $o = new Adapter();
        $o->hello();
        $o->world();
    }
}

Client::main();

对象适配

<?php
interface Target {
    public function hello();

    public function world();
}

class Adaptee {
    public function greet() {
        print_ln(__METHOD__);
    }

    public function world() {
        print_ln(__METHOD__);
    }
}

/**
* 通过包装Adaptee对象 对 target 接口 和 adaptee 具体实现适配
* client可随意选择合适的adaptee进行工作
* 必须要在Adapter中手动时间所有Target接口,具体工作由adaptee完成
*/
class Adapter implements Target {
    private $_adaptee;

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

    public function hello() {
        $this->_adaptee->greet();
    }

    public function world() {
        $this->_adaptee->world();
    }
}

class Client {
    public static function main() {
        $o = new Adapter(new Adaptee());
        $o->hello();
        $o->world();
    }
}

Client::main();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值