Bridge Pattern

Decouple an abstraction from its implementation so that the two can vary independently.


Purpose

Decouple an abstraction from its implementation so that the two can vary independently.

UML


Code

Formatter


namespace DesignPatterns\Structural\Bridge;

interface Formatter
{
    public function format(string $text): string;
}

Service


namespace DesignPatterns\Structural\Bridge;

abstract class Service
{
    public function __construct(protected Formatter $implementation)
    {
    }

    final public function setImplementation(Formatter $printer)
    {
        $this->implementation = $printer;
    }

    abstract public function get(): string;
}

HelloWorldService


namespace DesignPatterns\Structural\Bridge;

class HelloWorldService extends Service
{
    public function get(): string
    {
        return $this->implementation->format('Hello World');
    }
}

PingService


namespace DesignPatterns\Structural\Bridge;

class PingService extends Service
{
    public function get(): string
    {
        return $this->implementation->format('pong');
    }
}

PlainTextFormatter


namespace DesignPatterns\Structural\Bridge;

class PlainTextFormatter implements Formatter
{
    public function format(string $text): string
    {
        return $text;
    }
}

HtmlFormatter


namespace DesignPatterns\Structural\Bridge;

class HtmlFormatter implements Formatter
{
    public function format(string $text): string
    {
        return sprintf('

%s

', $text); } }

Tests


public function testCanPrintUsingThePlainTextFormatter()
{
    $service = new HelloWorldService(new PlainTextFormatter());

    $this->assertSame('Hello World', $service->get());
}

public function testCanPrintUsingTheHtmlFormatter()
{
    $service = new HelloWorldService(new HtmlFormatter());

    $this->assertSame('

Hello World

', $service->get()); }