php桥接模式(bridge pattern)

Posted aguncn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php桥接模式(bridge pattern)相关的知识,希望对你有一定的参考价值。

有点通了

<?php
/*
The bridge pattern is used when we want to decouple a class or abstraction from its
implementation, allowing them both to change independently. This is useful when
the class and its implementation vary often
*/

interface MessagingInterface 
    public function send($body);


class TextMessage implements MessagingInterface 
    public function send($body) 
        echo "TextMessage > send > $body: <br/>";
    


class htmlMessage implements MessagingInterface 
    public function send($body) 
        echo "HtmlMessage > send > $body: <br/>";
    


interface MailerInterface 
    public function setSender(MessagingInterface $sender);
    public function send($body);


abstract class Mailer implements MailerInterface 
    protected $sender;
    public function setSender(MessagingInterface $sender) 
        $this->sender = $sender;
    


class PHPMailer extends Mailer 
    public function send($body) 
        $body .= "\\n\\n Set from a phpmailer .";
        return $this->sender->send($body);
    


class SwiftMailer extends Mailer 
    public function send($body) 
        $body .= "\\n\\n Set from a swiftmailer .";
        return $this->sender->send($body);
    


$phpMailer = new PHPMailer();
$phpMailer->setSender(new TextMessage());
$phpMailer->send(‘Hi!‘);

$swiftMailer = new SwiftMailer();
$swiftMailer->setSender(new HtmlMessage());
$swiftMailer->send(‘Hello!‘);
?>

技术图片

以上是关于php桥接模式(bridge pattern)的主要内容,如果未能解决你的问题,请参考以下文章

桥接模式(Bridge Pattern)

设计模式 -- 桥接模式(Bridge Pattern)

桥接模式(Bridge Pattern)

C++设计模式——桥接模式(Bridge Pattern)

二十四种设计模式:桥接模式(Bridge Pattern)

9,桥接模式(Bridge Pattern)是将抽象部分与实际部分分离,使它们都可以独立的变化。