PHP设计模式 八
适配器模式
介绍
适配器模式是一种非常实用的结构型设计模式,核心作用是将一个类的接口转换成客户端所期望的另一个接口,从而让原本因接口不匹配而无法一起工作的类能够协同工作。
接口对接 多个第三方接口适配器接口适配器
调用适配器->通用方法(参数)
适用场景
集成遗留代码
旧系统的类功能完善但接口混乱,不想修改它,而是编写一个适配器供新系统调用。
统一多个第三方库的接口
比如项目同时使用了支付宝和微信支付,它们的 SDK 方法不同,可以分别写适配器让它们实现同一个支付接口。
数据库访问层
封装 MySQLi、PDO、Redis 等不同扩展,对外提供统一的查询、更新方法。
缓存系统
统一 文件缓存、Memcached、Redis 的 get()/set() 接口。
框架中的驱动体系
Laravel 的 Filesystem 适配器支持本地、S3、SFTP 等多种存储方式。
代码实现
发送接口
interface MessageSenderInterface{ public function send(string $to, string $content): bool;}
第三方接口
class SmsService{ public function sendSms(string $mobile, string $msg): bool {echo"真实发送短信到 {$mobile},内容:{$msg}\n";returntrue; }}
发送短信适配器
class SmsAdapter implements MessageSenderInterface{ private SmsService $smsService; public function __construct(SmsService $smsService) {$this->smsService = $smsService; } public function send(string $to, string $content): bool { // 转换参数名、顺序,甚至进行数据格式转换return$this->smsService->sendSms($to, $content); }}
class Sms{function send(MessageSenderInterface $sender, string $phone, string $text) {$sender->send($phone, $text); }}
调用
$phone = '13800138000';$content = '您的验证码是 1234';$sms = new Sms();$legacySms = new SmsService();// 使用适配器$adapter = new SmsAdapter($legacySms);$sms->sendSms($adapter,$phone , $content);