解耦一个对象使抽象与实现分离,这样二者能够独立地变化。php
<?php namespace DesignPatterns\Structural\Bridge; /** * 建立格式化接口。 */ interface FormatterInterface { public function format(string $text); }
<?php namespace DesignPatterns\Structural\Bridge; /** * 建立 PlainTextFormatter 文本格式类实现 FormatterInterface 接口。 */ class PlainTextFormatter implements FormatterInterface { /** * 返回字符串格式。 */ public function format(string $text) { return $text; } }
<?php namespace DesignPatterns\Structural\Bridge; /** * 建立 HtmlFormatter HTML 格式类实现 FormatterInterface 接口。 */ class HtmlFormatter implements FormatterInterface { /** * 返回 HTML 格式。 */ public function format(string $text) { return sprintf('<p>%s</p>', $text); } }
<?php namespace DesignPatterns\Structural\Bridge; /** * 建立抽象类 Service。 */ abstract class Service { /** * @var FormatterInterface * 定义实现属性。 */ protected $implementation; /** * @param FormatterInterface $printer * 传入 FormatterInterface 实现类对象。 */ public function __construct(FormatterInterface $printer) { $this->implementation = $printer; } /** * @param FormatterInterface $printer * 和构造方法的做用相同。 */ public function setImplementation(FormatterInterface $printer) { $this->implementation = $printer; } /** * 建立抽象方法 get() 。 */ abstract public function get(); }
<?php namespace DesignPatterns\Structural\Bridge; /** * 建立 Service 子类 HelloWorldService 。 */ class HelloWorldService extends Service { /** * 定义抽象方法 get() 。 * 根据传入的格式类定义来格式化输出 'Hello World' 。 */ public function get() { return $this->implementation->format('Hello World'); } }
<?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; /** * 建立自动化测试单元 BridgeTest 。 */ class BridgeTest extends TestCase { /** * 使用 HelloWorldService 分别测试文本格式实现类和 HTML 格式实 * 现类。 */ public function testCanPrintUsingThePlainTextPrinter() { $service = new HelloWorldService(new PlainTextFormatter()); $this->assertEquals('Hello World', $service->get()); // 如今更改实现方法为使用 HTML 格式器。 $service->setImplementation(new HtmlFormatter()); $this->assertEquals('<p>Hello World</p>', $service->get()); } }
PHP 互联网架构师 50K 成长指南+行业问题解决总纲(持续更新)sql
面试10家公司,收获9个offer,2020年PHP 面试问题shell
★若是喜欢个人文章,想与更多资深开发者一块儿交流学习的话,获取更多大厂面试相关技术咨询和指导,欢迎加入咱们的群啊,暗号:phpzh(群号码856460874)。设计模式
内容不错的话但愿你们支持鼓励下点个赞/喜欢,欢迎一块儿来交流;另外若是有什么问题 建议 想看的内容能够在评论提出架构