程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

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

发布于2021-03-14 05:49     阅读(628)     评论(0)     点赞(28)     收藏(2)


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

 

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

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

 

原文链接:https://www.cnblogs.com/taoshihan/p/13816696.html



所属网站分类: 技术文章 > 博客

作者:悲催的程序员

链接:http://www.phpheidong.com/blog/article/3056/4470b13c39043eb2913a/

来源:php黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

28 0
收藏该文
已收藏

评论内容:(最多支持255个字符)