1. 程式人生 > 實用技巧 >[PHP] 橋接模式-結構型設計模式

[PHP] 橋接模式-結構型設計模式

解耦一個物件的實現與抽象,這樣兩者可以獨立地變化。
對一個功能進行拆分成兩個具體物件,通過建構函式或者方法傳遞橋接起來兩個物件

通過傳遞另外物件來實現功能,本身保留抽象方法給子類去獨立實現

abstract class Service
{
    protected Formatter $implementation;
    public function __construct(Formatter $printer)
    {
        $this->implementation = $printer;
    }

    public function setImplementation(Formatter $printer)
    {
        $
this->implementation = $printer; } abstract public function get(): string; }

兩個子類實現同一個方法,不同的功能

class HelloWorldService extends Service
{
    public function get(): string
    {
        return $this->implementation->format('Hello World');
    }
}
class PingService extends Service
{
    
public function get(): string { return $this->implementation->format('pong'); } }

具體的功能實現由另外的獨立類來做,這樣兩個就可以獨立變化了

interface Formatter
{
    public function format(string $text): string;
}
class PlainTextFormatter implements Formatter
{
    public function format(string $text): string
{ return $text; } }

使用,現在它本身可以通過子類獨立變化,具體功能類可以傳遞進來,兩者也是各自獨立

$service = new HelloWorldService(new PlainTextFormatter());
$service->get();