layout | title | date | author | desc | in_head |
---|---|---|---|---|---|
post
|
PHP设计模式之桥接模式
|
2018-02-06 09:00:02 +0800
|
南丞
|
设计模式(Design Pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性。设计模式于己于他人于系统都是多赢的;设计模式使代码编制真正工程化;设计模式是软件工程的基石脉络,如同大厦的结构一样。
|
<style> .article-content p{ text-indent: 2em; line-height: 1.75rem; }</style>
|
桥接模式
<?php
header("Content-type: text/html; charset=utf-8");
require_once './vendor/autoload.php';
//场景:将对象与类型解耦,对象与类型之间可以随意关联调用
/**
* 抽象 道路
*/
abstract class Road
{
public $ICAR;
abstract public function RoRun();
}
/**
* 创建 告诉公路
*/
class SpeedRoad extends Road
{
public function RoRun()
{
$this->ICAR->IcRun();
echo '急速的行驶在高速公路上!<br>';
}
}
/**
* 创建 乡村小道
*/
class StreetRoad extends Road
{
public function RoRun()
{
$this->ICAR->IcRun();
echo '欢快的行驶在乡村小道上<br>';
}
}
/**
* 抽象接口 车
*/
interface ICAR
{
function IcRun();
}
/**
* 创建 轿车
*/
class Car implements ICAR
{
public function IcRun()
{
echo '玛莎拉蒂';
}
}
/**
* 创建 马车
*/
class Carriage implements ICAR
{
public function IcRun()
{
echo '马车';
}
}
# 让轿车跑到 乡村小道
$speedRoad=new StreetRoad(); // 先创建乡村小道
$speedRoad->ICAR=new Car(); // 再把轿车放到马路上
$speedRoad->RoRun();
# 让马车跑到 高速公路
$street=new SpeedRoad(); // 先创建高速公路
$street->ICAR=new Carriage(); // 再把马车放到马路上
$street->RoRun();