Middle+
What are the main principles and advantages of the Bridge design pattern?
sobes.tech AI
Answer from AI
Principles:
- Separates abstraction and implementation.
- Allows changing abstraction and implementation independently.
- Uses composition instead of inheritance to connect abstraction and implementation.
Advantages:
- Reduces the number of subclasses when there are many variations of abstraction and implementation.
- Allows adding new implementations without changing the abstraction.
- Allows adding new abstractions without changing existing implementations.
- 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.