รูปแบบการออกแบบ Bridge ใน PHP

Feb 23 2023
วิธีการใช้รูปแบบการออกแบบโครงสร้างนี้ใน PHP
รูปแบบการออกแบบสะพานคืออะไร? รูปแบบบริดจ์เป็นรูปแบบการออกแบบที่แยกสิ่งที่เป็นนามธรรมออกจากการนำไปใช้ เพื่อให้ทั้งสองสามารถเปลี่ยนแปลงได้อย่างอิสระ ใน PHP รูปแบบบริดจ์สามารถนำไปใช้ได้โดยใช้อินเตอร์เฟส คลาสนามธรรม และการสืบทอด
ภาพถ่ายโดย Aleksandr Barsukov บน Unsplash

รูปแบบการออกแบบสะพานคืออะไร?

รูปแบบบริดจ์เป็นรูปแบบการออกแบบที่แยกสิ่งที่เป็นนามธรรมออกจากการนำไปใช้ เพื่อให้ทั้งสองสามารถเปลี่ยนแปลงได้อย่างอิสระ

ใน PHP รูปแบบบริดจ์สามารถนำไปใช้ได้โดยใช้อินเตอร์เฟส คลาสนามธรรม และการสืบทอด

นี่คือตัวอย่างการใช้งานรูปแบบ Bridge ใน PHP:

<?php

interface DrawAPI {
    public function drawCircle($x, $y, $radius);
}

class DrawAPI1 implements DrawAPI {
    public function drawCircle($x, $y, $radius) {
        echo "API1.circle at ($x,$y) radius $radius.\n";
    }
}

class DrawAPI2 implements DrawAPI {
    public function drawCircle($x, $y, $radius) {
        echo "API2.circle at ($x,$y) radius $radius.\n";
    }
}

abstract class Shape {
    protected $drawAPI;
    
    protected function __construct(DrawAPI $drawAPI) {
        $this->drawAPI = $drawAPI;
    }
    
    public abstract function draw();
}

class CircleShape extends Shape {
    private $x, $y, $radius;
    
    public function __construct($x, $y, $radius, DrawAPI $drawAPI) {
        parent::__construct($drawAPI);
        $this->x = $x;
        $this->y = $y;
        $this->radius = $radius;
    }
    
    public function draw() {
        $this->drawAPI->drawCircle($this->x, $this->y, $this->radius);
    }
}

// Usage:
$shape1 = new CircleShape(1, 2, 3, new DrawAPI1());
$shape2 = new CircleShape(5, 7, 11, new DrawAPI2());

$shape1->draw(); // Output: API1.circle at (1,2) radius 3.
$shape2->draw(); // Output: API2.circle at (5,7) radius 11.

ด้วยการแยกสิ่งที่เป็นนามธรรม ( Shape) ออกจากการนำไปใช้ ( DrawAPI) เราสามารถเปลี่ยนแปลงแต่ละอย่างได้อย่างอิสระ ตัวอย่างเช่น เราสามารถเพิ่ม การใช้งานโดยไม่ต้องเปลี่ยน คลาสDrawAPI3ใดๆShape

ขอขอบคุณสำหรับเวลาของคุณ!

ฝากติดตามกันด้วยนะครับ!