目的
解耦一個物件使抽象與實作分離,這樣兩者可以獨立地變化,
例子

★官方PHP高級學習交流社群「點擊」管理整理了一些資料,BAT等一線大廠進階知識體系備好(相關學習資料以及筆面試題)以及不限于:分布式架構、高可擴展、高性能、高并發、服務器性能調優、TP6,laravel,YII2,Redis,Swoole、Swoft、Kafka、Mysql優化、shell腳本、Docker、微服務、Nginx等多個知識點高級進階干貨
代碼
- 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 互聯網架構師成長之路*「設計模式」終極指南
PHP 互聯網架構師 50K 成長指南+行業問題解決總綱(持續更新)
面試10家公司,識訓9個offer,2020年PHP 面試問題
★如果喜歡我的文章,想與更多資深開發者一起交流學習的話,獲取更多大廠面試相關技術咨詢和指導,歡迎加入我們的群啊,暗號:phpzh(群號碼856460874),
2020年最新PHP進階教程,全系列!

內容不錯的話希望大家支持鼓勵下點個贊/喜歡,歡迎一起來交流;另外如果有什么問題 建議 想看的內容可以在評論提出
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/39711.html
標籤:PHP
