程序開發中,我們面對不同的信息(M種信息,用不通的工具(N種工具)發送,按照單一職責原則,我們可能需要使用M*N種類來完成此項功能,這樣會使程序顯得非常臃腫,所以,需要用一種方式來完成此項工作-----橋接模式
原理:把發送工具(發送器),當做一個父類的一個屬性來調用發送工具中的方法,來進行消息發送。
//方法一
abstract class info
{
protected $send = null;
public function __construct($send)
{
$this->send = $send;
}
abstract public function msg($content);
public function send($to, $content)
{
$content = $this->msg($content);
$this->send->send($to, $content);
}
}
//信息的發送方式(發送器-發送工具)
class zn
{
public function send($to, $content)
{
echo '【站內給:'.$to, '】【內容是:'.$content.'】';
}
}
class email
{
public function send($to, $content)
{
echo '【Emal給:'.$to, '】【內容是:'.$content.'】';
}
}
class sms
{
public function send($to, $content)
{
echo '【SMS給:'.$to, '】【內容是:'.$content.'】';
}
}
//信息的緊急程度(消息緊急程度)
class commoninfo extends info
{
public function msg($content)
{
return '普通' . $content;
}
}
class warninfo extends info
{
public function msg($content)
{
return '緊急' . $content;
}
}
class dangerinfo extends info
{
public function msg($content)
{
return '特急' . $content;
}
}
//發送消息;
$sm=new commoninfo(new zn());
echo $sm->send('小明','喫飯了');
//通過接口規範-注入類的實例;
interface info
{
public function msg($to, $content);
}
interface MethodTool
{
public function send($to, $content);
}
//信息的發送方式
class zn implements MethodTool
{
public function send($to, $content)
{
echo '【站內給:' . $to, '】【內容是:' . $content . '】';
}
}
class email implements MethodTool
{
public function send($to, $content)
{
echo '【Emal給:' . $to, '】【內容是:' . $content . '】';
}
}
class sms implements MethodTool
{
public function send($to, $content)
{
echo '【SMS給:' . $to, '】【內容是:' . $content . '】';
}
}
//信息的緊急程度
class commoninfo implements info
{
protected $tool = null;
//這接通過接口注入類的實例
//後期如果添加新的信息注入方式,無需修改內部結構;
public function __construct(MethodTool $tool)
{
$this->tool = $tool;
}
public function msg($to, $content)
{
$info = '普通' . $content;
return $this->tool->send($to, $info);
}
}
class warninfo implements info
{
protected $tool = null;
public function __construct(MethodTool $tool)
{
$this->tool = $tool;
}
public function msg($to, $content)
{
$info = '緊急' . $content;
return $this->tool->send($to, $info);
}
}
class dangerinfo implements info
{
protected $tool = null;
public function __construct(MethodTool $tool)
{
$this->tool = $tool;
}
public function msg($to, $content)
{
$info = '特急' . $content;
return $this->tool->send($to, $info);
}
}
$sm = new commoninfo(new zn());
echo $sm->msg('小明', '喫飯了');