PHP設計模式之橋樑模式(Bridge)程式碼例項大全(11)
阿新 • • 發佈:2020-09-14
目的
解耦一個物件使抽象與實現分離,這樣兩者可以獨立地變化。
例子
程式碼
- Formatter.php
<?php namespace DesignPatterns\Structural\Bridge; /** * 建立格式化介面。 */ interface FormatterInterface { public function format(string $text); }
- PlainTextFormatter.php
<?php namespace DesignPatterns\Structural\Bridge; /** * 建立 PlainTextFormatter 文字格式類實現 FormatterInterface 介面。 */ class PlainTextFormatter implements FormatterInterface { /** * 返回字串格式。 */ public function format(string $text) { return $text; } }
- HtmlFormatter.php
<?php namespace DesignPatterns\Structural\Bridge; /** * 建立 HtmlFormatter HTML 格式類實現 FormatterInterface 介面。 */ class HtmlFormatter implements FormatterInterface { /** * 返回 HTML 格式。 */ public function format(string $text) { return sprintf('<p>%s</p>', $text); } }
- Service.php
<?php
namespace DesignPatterns\Structural\Bridge;
/**
* 建立抽象類 Service。
*/
abstract class Service
{
/**
* @var FormatterInterface
* 定義實現屬性。
*/
protected $implementation;
/**
* @param FormatterInterface $printer
* 傳入 FormatterInterface 實現類物件。
*/
public function __construct(FormatterInterface $printer)
{
$this->implementation = $printer;
}
/**
* @param FormatterInterface $printer
* 和構造方法的作用相同。
*/
public function setImplementation(FormatterInterface $printer)
{
$this->implementation = $printer;
}
/**
* 建立抽象方法 get() 。
*/
abstract public function get();
}
- HelloWorldService.php
<?php
namespace DesignPatterns\Structural\Bridge;
/**
* 建立 Service 子類 HelloWorldService 。
*/
class HelloWorldService extends Service
{
/**
* 定義抽象方法 get() 。
* 根據傳入的格式類定義來格式化輸出 'Hello World' 。
*/
public function get()
{
return $this->implementation->format('Hello World');
}
}
測試
- Tests/BridgeTest.php
<?php
namespace DesignPatterns\Structural\Bridge\Tests;
use DesignPatterns\Structural\Bridge\HelloWorldService;
use DesignPatterns\Structural\Bridge\HtmlFormatter;
use DesignPatterns\Structural\Bridge\PlainTextFormatter;
use PHPUnit\Framework\TestCase;
/**
* 建立自動化測試單元 BridgeTest 。
*/
class BridgeTest extends TestCase
{
/**
* 使用 HelloWorldService 分別測試文字格式實現類和 HTML 格式實
* 現類。
*/
public function testCanPrintUsingThePlainTextPrinter()
{
$service = new HelloWorldService(new PlainTextFormatter());
$this->assertEquals('Hello World', $service->get());
// 現在更改實現方法為使用 HTML 格式器。
$service->setImplementation(new HtmlFormatter());
$this->assertEquals('<p>Hello World</p>', $service->get());
}
}
PHP 網際網路架構師 50K 成長指南+行業問題解決總綱(持續更新)
面試10家公司,收穫9個offer,2020年PHP 面試問題
★如果喜歡我的文章,想與更多資深開發者一起交流學習的話,獲取更多大廠面試相關技術諮詢和指導,歡迎加入我們的群啊,暗號:phpzh(群號碼856460874)。
內容不錯的話希望大家支援鼓勵下點個贊/喜歡,歡迎一起來交流;另外如果有什麼問題 建議 想看的內容可以在評論提出