php设计模式-桥接模式

使用情景:系统通知用户,通知方式有站内信,邮件,手机短信3种方式,信的内容分普通,紧急两种程度,为了不避免两两组合,m* n种可能的搭配,使用桥接模式

// 抽象
abstract class Info{
    protected $_send = null; // 发送器 (site, email, sms);
    public function __construct($send)
    {
        $this->_send = $send;
    }
    abstract public function createContent($content);

    public function send($content)
    {
        $this->_send->send($content); // 调用不同发送器的发送方法
    }
}

// 消息发送方式
class SiteInfo // 站内信
{
    public function send($content)
    {
        echo '站内信:' . $content;
    }
}

class EmailInfo // 邮件
{
    public function send($content)
    {
        echo '邮件:' . $content;
    }
}

class SMSInfo // 手机短信
{
    public function send($content)
    {
        echo 'SMS:' . $content;
    }
}


// 消息紧急程度
class Common extends Info // 普通通知
{
    public function createContent($content)
    {
        return '普通-' . $content;
    }
}

class Urgent extends Info // 紧急通知
{
    public function createContent($content)
    {
        return '紧急-'  . $content;
    }
}

$common = new Common(new SMSInfo());
$content = $common->createContent('吃饭');
$common->send($content);
echo '<br>';
$common = new Urgent(new EmailInfo());
$content = $common->createContent('着火');
$common->send($content);

  结果:

SMS:普通-吃饭
邮件:紧急-着火

  

原文地址:https://www.cnblogs.com/xiangdongsheng/p/13369743.html