溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

PHP適配器模式怎么應(yīng)用

發(fā)布時(shí)間:2023-04-13 15:32:02 來(lái)源:億速云 閱讀:94 作者:iii 欄目:編程語(yǔ)言

今天小編給大家分享一下PHP適配器模式怎么應(yīng)用的相關(guān)知識(shí)點(diǎn),內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識(shí),所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來(lái)了解一下吧。

PHP 適配器模式講解和代碼示例

適配器是一種結(jié)構(gòu)型設(shè)計(jì)模式, 它能使不兼容的對(duì)象能夠相互合作。

適配器可擔(dān)任兩個(gè)對(duì)象間的封裝器, 它會(huì)接收對(duì)于一個(gè)對(duì)象的調(diào)用, 并將其轉(zhuǎn)換為另一個(gè)對(duì)象可識(shí)別的格式和接口。

復(fù)雜度:******

流行度:******

使用示例: 適配器模式在 PHP 代碼中很常見(jiàn)。 基于一些遺留代碼的系統(tǒng)常常會(huì)使用該模式。 在這種情況下, 適配器讓遺留代碼與現(xiàn)代的類得以相互合作。

識(shí)別方法: 適配器可以通過(guò)以不同抽象或接口類型實(shí)例為參數(shù)的構(gòu)造函數(shù)來(lái)識(shí)別。 當(dāng)適配器的任何方法被調(diào)用時(shí), 它會(huì)將參數(shù)轉(zhuǎn)換為合適的格式, 然后將調(diào)用定向到其封裝對(duì)象中的一個(gè)或多個(gè)方法。

  • 真實(shí)世界示例

適配器允許你使用第三方或遺留系統(tǒng)的類, 即使它們與你的代碼不兼容。 例如, 你可以創(chuàng)建一系列特殊的封裝器, 來(lái)讓應(yīng)用所發(fā)出的調(diào)用與第三方類所要求的接口與格式適配, 而無(wú)需重寫應(yīng)用的通知接口以使其支持每一個(gè)第三方服務(wù) (如釘釘、 微信、 短信或其他任何服務(wù))。

index.php: 真實(shí)世界示例

<?php

namespace RefactoringGuru\Adapter\RealWorld;

/**
* The Target interface represents the interface that your application's classes
* already follow.
*/
interface Notification
{
   public function send(string $title, string $message);
}

/**
* Here's an example of the existing class that follows the Target interface.
*
* The truth is that many real apps may not have this interface clearly defined.
* If you're in that boat, your best bet would be to extend the Adapter from one
* of your application's existing classes. If that's awkward (for instance,
* SlackNotification doesn't feel like a subclass of EmailNotification), then
* extracting an interface should be your first step.
*/
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 "Sent email with title '$title' to '{$this->adminEmail}' that says '$message'.";
   }
}

/**
* The Adaptee is some useful class, incompatible with the Target interface. You
* can't just go in and change the code of the class to follow the Target
* interface, since the code might be provided by a 3rd-party library.
*/
class SlackApi
{
   private $login;
   private $apiKey;

   public function __construct(string $login, string $apiKey)
   {
       $this->login = $login;
       $this->apiKey = $apiKey;
   }

   public function logIn(): void
   {
       // Send authentication request to Slack web service.
       echo "Logged in to a slack account '{$this->login}'.\n";
   }

   public function sendMessage(string $chatId, string $message): void
   {
       // Send message post request to Slack web service.
       echo "Posted following message into the '$chatId' chat: '$message'.\n";
   }
}

/**
* The Adapter is a class that links the Target interface and the Adaptee class.
* In this case, it allows the application to send notifications using Slack
* API.
*/
class SlackNotification implements Notification
{
   private $slack;
   private $chatId;

   public function __construct(SlackApi $slack, string $chatId)
   {
       $this->slack = $slack;
       $this->chatId = $chatId;
   }

   /**
    * An Adapter is not only capable of adapting interfaces, but it can also
    * convert incoming data to the format required by the Adaptee.
    */
   public function send(string $title, string $message): void
   {
       $slackMessage = "#" . $title . "# " . strip_tags($message);
       $this->slack->logIn();
       $this->slack->sendMessage($this->chatId, $slackMessage);
   }
}

/**
* The client code can work with any class that follows the Target interface.
*/
function clientCode(Notification $notification)
{
   // ...

   echo $notification->send("Website is down!",
       "<strong style='color:red;font-size: 50px;'>Alert!</strong> " .
       "Our website is not responding. Call admins and bring it up!");

   // ...
}

echo "Client code is designed correctly and works with email notifications:\n";
$notification = new EmailNotification("developers@example.com");
clientCode($notification);
echo "\n\n";


echo "The same client code can work with other classes via adapter:\n";
$slackApi = new SlackApi("example.com", "XXXXXXXX");
$notification = new SlackNotification($slackApi, "Example.com Developers");
clientCode($notification);

Output.txt: 執(zhí)行結(jié)果

Client code is designed correctly and works with email notifications:
Sent email with title 'Website is down!' to 'developers@example.com' that says '<strong style='color:red;font-size: 50px;'>Alert!</strong> Our website is not responding. Call admins and bring it up!'.
The same client code can work with other classes via adapter:
Logged in to a slack account 'example.com'.
Posted following message into the 'Example.com Developers' chat: '#Website is down!# Alert! Our website is not responding. Call admins and bring it up!'.
  • 概念示例

本例說(shuō)明了適配器設(shè)計(jì)模式的結(jié)構(gòu)并重點(diǎn)回答了下面的問(wèn)題:

  • 它由哪些類組成?

  • 這些類扮演了哪些角色?

  • 模式中的各個(gè)元素會(huì)以何種方式相互關(guān)聯(lián)?

了解該模式的結(jié)構(gòu)后, 你可以更容易地理解下面基于真實(shí)世界的 PHP 應(yīng)用案例。

index.php:  概念示例
<?php

namespace RefactoringGuru\Adapter\Conceptual;

/**
* The Target defines the domain-specific interface used by the client code.
*/
class Target
{
   public function request(): string
   {
       return "Target: The default target's behavior.";
   }
}

/**
* The Adaptee contains some useful behavior, but its interface is incompatible
* with the existing client code. The Adaptee needs some adaptation before the
* client code can use it.
*/
class Adaptee
{
   public function specificRequest(): string
   {
       return ".eetpadA eht fo roivaheb laicepS";
   }
}

/**
* The Adapter makes the Adaptee's interface compatible with the Target's
* interface.
*/
class Adapter extends Target
{
   private $adaptee;

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

   public function request(): string
   {
       return "Adapter: (TRANSLATED) " . strrev($this->adaptee->specificRequest());
   }
}

/**
* The client code supports all classes that follow the Target interface.
*/
function clientCode(Target $target)
{
   echo $target->request();
}

echo "Client: I can work just fine with the Target objects:\n";
$target = new Target();
clientCode($target);
echo "\n\n";

$adaptee = new Adaptee();
echo "Client: The Adaptee class has a weird interface. See, I don't understand it:\n";
echo "Adaptee: " . $adaptee->specificRequest();
echo "\n\n";

echo "Client: But I can work with it via the Adapter:\n";
$adapter = new Adapter($adaptee);
clientCode($adapter);
Output.txt:  執(zhí)行結(jié)果
Client: I can work just fine with the Target objects:
Target: The default target's behavior.

Client: The Adaptee class has a weird interface. See, I don't understand it:
Adaptee: .eetpadA eht fo roivaheb laicepS

Client: But I can work with it via the Adapter:
Adapter: (TRANSLATED) Special behavior of the Adaptee.

以上就是“PHP適配器模式怎么應(yīng)用”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會(huì)為大家更新不同的知識(shí),如果還想學(xué)習(xí)更多的知識(shí),請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI