Инструменты пользователя

Инструменты сайта


php:shablony_proektirovanija:structural_patterns:bridge

Это старая версия документа!


Мост (Bridge)

Назначение

Отделить абстракцию от её реализации так, что они могут изменяться независимо друг от друга.

Диаграмма UML

Alt Bridge UML Diagram

Код

Вы можете найти этот код на GitHub

Formatter.php

<?php
 
declare(strict_types=1);
 
namespace DesignPatterns\Structural\Bridge;
 
interface Formatter
{
    public function format(string $text): string;
}

PlainTextFormatter.php

<?php
 
declare(strict_types=1);
 
namespace DesignPatterns\Structural\Bridge;
 
class PlainTextFormatter implements Formatter
{
    public function format(string $text): string
    {
        return $text;
    }
}

HtmlFormatter.php

<?php
 
declare(strict_types=1);
 
namespace DesignPatterns\Structural\Bridge;
 
class HtmlFormatter implements Formatter
{
    public function format(string $text): string
    {
        return sprintf('<p>%s</p>', $text);
    }
}

Service.php

<?php
 
declare(strict_types=1);
 
namespace DesignPatterns\Structural\Bridge;
 
abstract class Service
{
    public function __construct(protected Formatter $implementation)
    {
    }
 
    public function setImplementation(Formatter $printer)
    {
        $this->implementation = $printer;
    }
 
    abstract public function get(): string;
}

HelloWorldService.php

<?php
 
declare(strict_types=1);
 
namespace DesignPatterns\Structural\Bridge;
 
class HelloWorldService extends Service
{
    public function get(): string
    {
        return $this->implementation->format('Hello World');
    }
}

PingService.php

<?php
 
declare(strict_types=1);
 
namespace DesignPatterns\Structural\Bridge;
 
class PingService extends Service
{
    public function get(): string
    {
        return $this->implementation->format('pong');
    }
}

Тест

Tests/BridgeTest.php

<?php
 
declare(strict_types=1);
 
namespace DesignPatterns\Structural\Bridge\Tests;
 
use DesignPatterns\Structural\Bridge\HelloWorldService;
use DesignPatterns\Structural\Bridge\HtmlFormatter;
use DesignPatterns\Structural\Bridge\PlainTextFormatter;
use PHPUnit\Framework\TestCase;
 
class BridgeTest extends TestCase
{
    public function testCanPrintUsingThePlainTextFormatter()
    {
        $service = new HelloWorldService(new PlainTextFormatter());
 
        $this->assertSame('Hello World', $service->get());
    }
 
    public function testCanPrintUsingTheHtmlFormatter()
    {
        $service = new HelloWorldService(new HtmlFormatter());
 
        $this->assertSame('<p>Hello World</p>', $service->get());
    }
}
php/shablony_proektirovanija/structural_patterns/bridge.1691438146.txt.gz · Последние изменения: 2023/08/07 22:55 — werwolf