ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 示例 适配器模式在 PHP 代码中很常见。基于一些遗留代码的系统常常会使用该模式。在这种情况下,适配器让遗留代码与现代的类得以相互合作 ### 概念示例 <details> <summary>main.php</summary> ``` <?php class Target { public function request(): string { return "Target: The default target's behavior."; } } // 适配行为 class Adaptee { public function specificRequest(): string { return ".eetpadA eht fo roivaheb laicepS"; } } // 添加适配器,来适配 target class Adapter extends Target { private $adaptee; public function __construct(Adaptee $adaptee) { $this->adaptee = $adaptee; } public function request(): string { return strrev($this->adaptee->specificRequest()); } } function clientCode(Target $target) { echo $target->request(); } $adaptee = new Adaptee(); $adapter = new Adapter($adaptee); clientCode($adapter); ``` </details> <br /> 输出 ``` Special behavior of the Adaptee. ``` ### 改造邮箱发送接口 适配器允许你使用第三方或遗留系统的类, 即使它们与你的代码不兼容 你可以创建一系列特殊的封装器,来让应用所发出的调用与第三方类所要求的接口与格式适配,而无需重写应用的通知接口以使其支持每一个第三方服务(如钉钉、微信、短信或其他任何服务) <details> <summary>main.php</summary> ``` <?php interface Notification { public function send(string $title, string $message); } // 假设原先为发邮箱的接口 class EmailNotification implements Notification { private $adminEmail; public function __construct(string $adminEmail) { $this->adminEmail = $adminEmail; } public function send(string $title, string $message): void { mail($this->adminEmail, $title, $message); echo "send email :'$title' to '{$this->adminEmail}' that says '$message'."; } } class SlackApi { private $login; private $apiKey; public function __construct(string $login, string $apiKey) { $this->login = $login; $this->apiKey = $apiKey; } public function logIn(): void { echo "logIn :'{$this->login}'.\n"; } public function sendMessage(string $chatId, string $message): void { echo "sendMessage :'$chatId' chat: '$message'.\n"; } } class SlackNotification implements Notification { private $slack; private $chatId; public function __construct(SlackApi $slack, string $chatId) { $this->slack = $slack; $this->chatId = $chatId; } // 对发邮箱接口进行适配 public function send(string $title, string $message): void { // strip_tags 可以去掉原先邮箱发送时候携带的 html标签 $slackMessage = "#" . $title . "# " . strip_tags($message); $this->slack->logIn(); $this->slack->sendMessage($this->chatId, $slackMessage); } } // 假设为老代码的调用通知接口 function clientCode(Notification $notification) { // ... echo $notification->send("发送 title","<p>发送内容</p>"); // ... } $notification = new EmailNotification("developers@example.com"); clientCode($notification); echo "\n\n"; $slackApi = new SlackApi("example.com", "XXXXXXXX"); $notification = new SlackNotification($slackApi, "Example.com Developers"); clientCode($notification); ``` </details> <br /> 输出 ``` Sent email with title '发送 title' to 'developers@example.com' that says '<p>发送内容</p>'. logIn :'example.com'. sendMessage :'Example.com Developers' chat: '#发送 title# 发送内容'. ```