PHP의 Bridge 디자인 패턴

Feb 23 2023
PHP에서 이 구조 설계 패턴을 구현하는 방법
브리지 디자인 패턴이란 무엇입니까? 브리지 패턴은 구현에서 추상화를 분리하여 둘이 독립적으로 변경될 수 있도록 하는 디자인 패턴입니다. PHP에서 브리지 패턴은 인터페이스, 추상 클래스 및 상속을 사용하여 구현할 수 있습니다.
Unsplash에 있는 Aleksandr Barsukov의 사진

브리지 디자인 패턴이란 무엇입니까?

브리지 패턴은 구현에서 추상화를 분리하여 둘이 독립적으로 변경될 수 있도록 하는 디자인 패턴입니다.

PHP에서 브리지 패턴은 인터페이스, 추상 클래스 및 상속을 사용하여 구현할 수 있습니다.

다음은 PHP에서 Bridge 패턴을 구현한 예입니다.

<?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.

시간 내 주셔서 감사합니다!

편하게 팔로우 해주세요!