前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[PHP] 桥接模式-结构型设计模式

[PHP] 桥接模式-结构型设计模式

作者头像
唯一Chat
发布2020-10-27 17:33:03
2230
发布2020-10-27 17:33:03
举报
文章被收录于专栏:陶士涵的菜地

解耦一个对象的实现与抽象,这样两者可以独立地变化。 对一个功能进行拆分成两个具体对象,通过构造函数或者方法传递桥接起来两个对象

通过传递另外对象来实现功能,本身保留抽象方法给子类去独立实现

代码语言:javascript
复制
abstract class Service
{
    protected Formatter $implementation;
    public function __construct(Formatter $printer)
    {
        $this->implementation = $printer;
    }

    public function setImplementation(Formatter $printer)
    {
        $this->implementation = $printer;
    }
    abstract public function get(): string;
}

两个子类实现同一个方法,不同的功能

代码语言:javascript
复制
class HelloWorldService extends Service
{
    public function get(): string
    {
        return $this->implementation->format('Hello World');
    }
}
class PingService extends Service
{
    public function get(): string
    {
        return $this->implementation->format('pong');
    }
}

具体的功能实现由另外的独立类来做,这样两个就可以独立变化了

代码语言:javascript
复制
interface Formatter
{
    public function format(string $text): string;
}
class PlainTextFormatter implements Formatter
{
    public function format(string $text): string
    {
        return $text;
    }
}

使用,现在它本身可以通过子类独立变化,具体功能类可以传递进来,两者也是各自独立

代码语言:javascript
复制
$service = new HelloWorldService(new PlainTextFormatter());
$service->get();
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-10-14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档