Bridge

Purpose:

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

FormatterInterface.php

<?php 

namespace DesignPatterns\Structural\Bridge;

interface FormatterInterface
{
    public function format(string $text);
}
?>

  

PlainTextFormatter.php

<?php 

namespace DesignPatterns\Structural\Bridge;

class PlainTextFormatter implements FormatterInterface
{
    /**
        * Function Description
        *
        * @return string
    */
    public function format(string $text): string
    {
        return $text
    }
}
?>

  

HtmlFormatter.php

<?php 

namespace DesignPatterns\Structural\Bridge;

class HtmlFormatter implements FormatterInterface
{
    /**
        * Function Description
        *
        * @return string
    */
    public function format(string $text)
    {
        return sprintf('<p>%s</p>', $text);
    }
}
?>

  

Service.php

<?php 

namespace DesignPatterns\Structural\Bridge;

abstract class Service 
{
    /**
        * Varibles Description
        *
        * @var FormatterInterface
    */
    protected $implementation;

    /**
        * Constructor
        *
        * @return Void
    */
    public function __construct(FormatterInterface $printer)
    {
        $this->implementation = $printer;
    }

    /**
        * Function Description
        *
        * @return Void
    */
    public function setImplementation(FormatterInterface $printer)
    {
        $this->implementation = $printer;
    }

    abstract public function get();
}

?>

  

HelloWorldService.php

<?php 

namespace DesignPatterns\Structural\Bridge;

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

  

Tests/BridgeTest.php

<?php

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 testCanPrintUsingThePlainTextPrinter()
    {
        $service = new HelloWorldService(new PlainTextFormatter());
        $this->assertEquals('Hello World', $service->get());

        // now change the implementation and use the HtmlFormatter instead
        $service->setImplementation(new HtmlFormatter());
        $this->assertEquals('<p>Hello World</p>', $service->get());
    }
}

  

posted @ 2019-05-08 18:12  Victor!!!!  阅读(181)  评论(0)    收藏  举报