Sobes.tech
Middle+

What are the main principles and advantages of the Bridge design pattern?

sobes.tech AI

Answer from AI

Principles:

  1. Separates abstraction and implementation.
  2. Allows changing abstraction and implementation independently.
  3. Uses composition instead of inheritance to connect abstraction and implementation.

Advantages:

  1. Reduces the number of subclasses when there are many variations of abstraction and implementation.
  2. Allows adding new implementations without changing the abstraction.
  3. Allows adding new abstractions without changing existing implementations.
  4. Increases system flexibility.

Example structure:

<?php
// Abstraction
abstract class Abstraction
{
    protected Implementor $implementor;

    public function __construct(Implementor $implementor)
    {
        $this->implementor = $implementor;
    }

    abstract public function operation(): string;
}

// Refined abstraction
class RefinedAbstraction extends Abstraction
{
    public function operation(): string
    {
        return "RefinedAbstraction: " . $this->implementor->operationImplementor();
    }
}

// Implementor interface
interface Implementor
{
    public function operationImplementor(): string;
}

// Concrete implementations
class ConcreteImplementorA implements Implementor
{
    public function operationImplementor(): string
    {
        return "ConcreteImplementorA operation.";
    }
}

class ConcreteImplementorB implements Implementor
{
    public function operationImplementor(): string
    {
        return "ConcreteImplementorB operation.";
    }
}

// Usage example
$implementorA = new ConcreteImplementorA();
$abstractionA = new RefinedAbstraction($implementorA);
echo $abstractionA->operation(); // Output: RefinedAbstraction: ConcreteImplementorA operation.

$implementorB = new ConcreteImplementorB();
$abstractionB = new RefinedAbstraction($implementorB);
echo $abstractionB->operation(); // Output: RefinedAbstraction: ConcreteImplementorB operation.