>  기사  >  백엔드 개발  >  PHP设计模式之桥接模式

PHP设计模式之桥接模式

WBOY
WBOY원래의
2016-06-20 12:28:25798검색

桥接模式属于结构型模式,何为结构型模式,即结构型设计模式是从程序的结构上解决模块之间的耦合问题(低耦合)

概述:将抽象部分与它的实现部分分离,使他们都可以独立的变化

桥接模式:

将抽象部分与它的实现部分分离,使他们都可以独立的变

抽象与它的实现分离,即抽象类和它的派生类用来实现自己的对象

桥接与适配器模式的关系(适配器模式后面讲解)

桥接属于聚合关系,两者关联 但不继承

适配器属于组合关系,适配者需要继承源

聚合关系:A对象可以包含B对象 但B对象不是A对象的一部分

个人举例:

1 大雁和雁群

2 手机软件和手机品牌功能

组成关系:

鸟和翅膀的关系

namespace haibao\design\web\view\design;

use haibao\design\web\common\design\bridge\PhoneBrandNokia;

use haibao\design\web\common\design\bridge\PhoneBrandApple;

use haibao\design\web\common\design\bridge\PhoneGame;

use haibao\design\web\common\design\bridge\PhoneList;

class Bridge extends \haibao\design\web\view\Base{

protected function preRender(){

header("Content-type: text/html; charset=utf-8");

$nokia = new PhoneBrandNokia();

$nokia->setPhoneSoft(new PhoneGame('诺基亚'));

$nokia->run();

echo '
';

$nokia->setPhoneSoft(new PhoneList('诺基亚'));

$nokia->run();

echo '
';

$apple = new PhoneBrandApple();

$apple->setPhoneSoft(new PhoneGame('苹果'));

$apple->run();

echo '
';

$apple->setPhoneSoft(new PhoneList('苹果'));

$apple->run();

echo '
';

}

}

/**

* 手机品牌

*/

namespace haibao\design\web\common\design\bridge;

abstract class PhoneBrand{

public $phoneSoft;

public function setPhoneSoft($phoneSoft){

$this->phoneSoft = $phoneSoft;

}

public function run(){}

}

/**

* 苹果

*/

namespace haibao\design\web\common\design\bridge;

class PhoneBrandApple extends PhoneBrand{

public function run(){

$this->phoneSoft->run();

}

}

/**

* 诺基亚

*/

namespace haibao\design\web\common\design\bridge;

class PhoneBrandNokia extends PhoneBrand{

public function run(){

$this->phoneSoft->run();

}

}

/**

* 手机游戏

*/

namespace haibao\design\web\common\design\bridge;

class PhoneGame extends PhoneSoft{

public $name;

public function __construct($name){

$this->name = $name;

}

public function run(){

echo '运行'.$this->name.'平台手机游戏';

}

}

/**

* 手机通讯录

*/

namespace haibao\design\web\common\design\bridge;

class PhoneList extends PhoneSoft{

public $name;

public function __construct($name){

$this->name = $name;

}

public function run(){

echo '运行'.$this->name.'手机通讯录';

}

}

/**

* 手机软件

*/

namespace haibao\design\web\common\design\bridge;

abstract class PhoneSoft{

public function run(){}

}

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.