
作用說明
1.橋接模式分離抽象介面及其實作部分,實現解耦,比繼承更好的解決方案。
2.方便擴展,橋接模式比繼承更靈活,在減少創建類別的同時也便於組合。
3.橋接模式可用於兩個獨立變化維度。
實例
// 員工分組
abstract class Staff
{
abstract public function staffData();
}
class CommonStaff extends Staff
{
public function staffData()
{
return "小名,小紅,小黑";
}
}
class VipStaff extends Staff
{
public function staffData()
{
return '小星、小龍';
}
}
// 傳送形式
// 抽象父類別abstract class SendType
{
abstract public function send($to, $content);
}
class QQSend extends SendType
{
public function __construct()
{
// 與QQ介面連接方式 }
public function 資訊($to, $content)
{
return $content. '(To '. $to . ' From QQ)<br>';
}
}
class SendInfo
{
protected $_level;
protected $_method;
public function __construct($level, $method)
{
// 這裡可以使用單例來控制資源的消耗 $this->_level = $level;
$this->_method = $method;
}
public function sending($content)
{
$staffArr = $this->_level->staffData();
$result = $this->_method->send($staffArr, $content);
echo $result;
}
}
// 客戶端調用
$info = new SendInfo(new VipStaff(), new QQSend());
$info->sending( '回家吃飯');
$info = new SendInfo(new CommonStaff(), new QQSend());
$info->sending( '繼續上班');
輸出結果:
回家吃飯(To 小星、小龍 From QQ)
繼續上班(To 小名,小紅,小黑 From QQ)以上就是php橋接模式的作用,希望對大家有幫助。