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

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

 

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

复制代码
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;
}
复制代码

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

复制代码
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');
    }
}
复制代码

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

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

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

$service = new HelloWorldService(new PlainTextFormatter());
$service->get();

 

posted @   唯一客服系统开发笔记  阅读(185)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-10-14 [视频教程] 配置vscode的PHP自动补全提示与使用Xdebug进行远程调试debug
点击右上角即可分享
微信分享提示
1
chat with us