W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
解耦一個對象的實現(xiàn)與抽象,這樣兩者可以獨立地變化。
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());
}
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: