橋樑模式(Bridge Pattern)以PHP為例
橋樑模式(Bridge Pattern)是一種結構型設計模式,它將抽象和實作分離,使它們可以獨立變化。這種模式通常用於將類別的抽象部分與其實作部分分離,並且可以獨立地擴展和修改它們。
以下是一個使用 PHP 語言的橋樑模式重構案例:
// 實作部分的介面
interface Implementation {
public function operationImplementation(): string;
}
// 具體的實作部分 A
class ConcreteImplementationA implements Implementation {
public function operationImplementation(): string {
return "ConcreteImplementationA";
}
}
// 具體的實作部分 B
class ConcreteImplementationB implements Implementation {
public function operationImplementation(): string {
return "ConcreteImplementationB";
}
}
// 抽象部分的類別
abstract class Abstraction {
protected $implementation;
public function __construct(Implementation $implementation) {
$this->implementation = $implementation;
}
public function operation(): string {
return "Abstraction: " . $this->implementation->operationImplementation();
}
}
// 擴充抽象部分的類別
class RefinedAbstraction extends Abstraction {
public function operation(): string {
return "RefinedAbstraction: " . $this->implementation->operationImplementation();
}
}
// 使用範例
$implementationA = new ConcreteImplementationA();
$abstraction = new RefinedAbstraction($implementationA);
echo $abstraction->operation(); // Output: RefinedAbstraction: ConcreteImplementationA
$implementationB = new ConcreteImplementationB();
$abstraction->setImplementation($implementationB);
echo $abstraction->operation(); // Output: RefinedAbstraction: ConcreteImplementationB
在這個例子中,我們首先定義了一個實作部分的介面 `Implementation`,並實作了兩個具體的實作部分類別 `ConcreteImplementationA` 和 `ConcreteImplementationB`。
然後,我們定義了抽象部分的類別 `Abstraction`,它包含了一個對實作部分的參考。在抽象類別中,我們定義了一個操作方法 `operation`,它使用實作部分的方法 `operationImplementation`。
接著,我們擴充了抽象部分的類別,創建了一個 `RefinedAbstraction` 類別,並覆寫了操作方法 `operation`。
最後,我們使用範例中的實作部分和抽象部分,創建了一個具體的橋樑物件 `abstraction`,並呼叫其操作方法。根據設定的實作部分,操作方法的輸出會有所不同。
透過橋樑模式,我們可以將抽象部分和實作部分解耦,使它們可以獨立地變化和擴展。這種設計模式對於應對變化和保持程式碼彈性非常有用。
留言
張貼留言