解耦一個物件的實作與抽象,這樣兩者可以獨立地變化,
對一個功能進行拆分成兩個具體物件,通過建構式或者方法傳遞橋接起來兩個物件
通過傳遞另外物件來實作功能,本身保留抽象方法給子類去獨立實作
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();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/172522.html
標籤:PHP
