您的位置:58编程 > 桥接模式csdn PHP 桥接模式

桥接模式csdn PHP 桥接模式

2023-05-13 14:33 PHP设计模式

桥接模式csdn PHP 桥接模式

桥接模式csdn PHP 桥接模式

桥接模式csdn

目的

解耦一个对象的实现与抽象,这样两者可以独立地变化。

UML 图

Alt Bridge UML Diagram

代码

Formatter.php

<?php

declare(strict_types=1);

namespace DesignPatternsStructuralBridge;

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

PlainTextFormatter.php

<?php

declare(strict_types=1);

namespace DesignPatternsStructuralBridge;

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

HtmlFormatter.php

<?php

declare(strict_types=1);

namespace DesignPatternsStructuralBridge;

class HtmlFormatter implements Formatter
{
    public function format(string $text): string
    {
        return sprintf("<p>%s</p>", $text);
    }
}

Service.php

<?php

declare(strict_types=1);

namespace DesignPatternsStructuralBridge;

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 DesignPatternsStructuralBridge;

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

PingService.php

<?php

declare(strict_types=1);

namespace DesignPatternsStructuralBridge;

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

测试

Tests/BridgeTest.php

<?php

declare(strict_types=1);

namespace DesignPatternsStructuralBridgeTests;

use DesignPatternsStructuralBridgeHelloWorldService;
use DesignPatternsStructuralBridgeHtmlFormatter;
use DesignPatternsStructuralBridgePlainTextFormatter;
use PHPUnitFrameworkTestCase;

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());
    }
}


阅读全文
以上是58编程为你收集整理的桥接模式csdn PHP 桥接模式全部内容。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。
相关文章
© 2024 58编程 58biancheng.com 版权所有 联系我们
桂ICP备12005667号-32 Powered by CMS