PHP設計模式—橋接模式
阿新 • • 發佈:2021-06-29
定義:
橋接模式(Bridge):將抽象部分與它的實現部分分離,使它們都可以獨立地變化。
結構:
- Abstraction:抽象類。
- RefindAbstraction:被提煉的抽象類。
- Implementor:實現類。
- ConcreteImplementor:具體實現類 。
- Client:客戶端程式碼。
程式碼例項:
接下來用程式碼實現一個顏色組合的例子,有三種顏色:黑、白、紅,三種形狀:圓形、正方形、長方形,可以自由組合。在這個例子中Abstraction表示形狀,RefindAbstraction表示圓形、正方形、長方形,Implementor表示顏色,ConcreteImplementor表示黑、白、紅。
/** * 顏色抽象類 * Class Colour */ abstract class Colour { /** * @return mixed */ abstract public function run(); } /** * 黑色 * Class Black */ class Black extends Colour { public function run() { // TODO: Implement run() method. return '黑色'; } } /** * 白色 * Class White*/ class White extends Colour { public function run() { // TODO: Implement run() method. return '白色'; } } /** * 紅色 * Class Red */ class Red extends Colour { public function run() { // TODO: Implement run() method. return '紅色'; } } /** * 形狀抽象類 * Class Shape*/ abstract class Shape { /** * 顏色 * @var Colour */ protected $colour; /** * Shape constructor. * @param Colour $colour */ public function __construct(Colour $colour) { $this->colour = $colour; } /** * @return mixed */ abstract public function operation(); } /** * 圓形 * Class Round */ class Round extends Shape { /** * @return mixed|void */ public function operation() { // TODO: Implement operation() method. echo $this->colour->run() . '圓形<br>'; } } /** * 長方形 * Class Rectangle */ class Rectangle extends Shape { /** * @return mixed|void */ public function operation() { // TODO: Implement operation() method. echo $this->colour->run() . '長方形<br>'; } } /** * 正方形 * Class Square */ class Square extends Shape { /** * @return mixed|void */ public function operation() { // TODO: Implement operation() method. echo $this->colour->run() . '正方形<br>'; } } // 客戶端程式碼 // 白色圓形 $whiteRound = new Round(new White()); $whiteRound->operation(); // 黑色正方形 $blackSquare = new Square(new Black()); $blackSquare->operation(); // 紅色長方形 $redRectangle = new Rectangle(new Red()); $redRectangle->operation(); // 執行結果 白色圓形 黑色正方形 紅色長方形
總結:
- 橋接模式分離抽象介面及其實現部分,實現解耦,相比繼承而言,無疑是一個更好的解決方案。
- 方便擴充套件,橋接模式相比繼承而言更加靈活,減少建立類的同時還方便組合。
- 對於兩個獨立變化的維度,可以使用橋接模式。