PHP设计模式-桥接模式

2019-02-17  本文已影响0人  木有sky

适用性

基础的结构型设计模式:将抽象和实现解耦,对抽象的实现是实体行为对接口的实现。

例如:人 => 抽象为属性:性别 动作:吃 => 人吃的动作抽象为interface => 实现不同的吃法。

UML

代码示例

/**

* 人抽象类

*/

abstract class PersonAbstract

{

    /**

    * 性别

    * @var string

    */

    protected $_gender = '';

    /**

    * 使用的吃饭工具

    * @var string

    */

    protected $_tool  = '';

    /**

    * 构造函数

    *

    * @param string      $gender 性别

    * @param EatInterface $tool  [description]

    */

    public function __construct($gender='',EatInterface $tool)

    {

        $this->_gender = $gender;

        $this->_tool  = $tool;

    }

    /**

    * 吃的行为

    *

    * @param  string $food 实物

    * @return void

    */

    abstract public function eat($food='');

}

/**

* 男人实类

*/

class PersonMale extends PersonAbstract

{

    /**

    * 吃的具体方式

    *

    * @param  string $food 食物

    * @return string

    */

    public function eat($food='')

    {

        $this->_tool->eat($food);

    }

}

/**

* 吃接口

*/

interface EatInterface

{

    /**

    * 吃

    *

    * @param  string $food 食物

    * @return mixed

    */

    public function eat($food='');

}

/**

* 用叉子吃实体

*/

class EatByFork implements EatInterface

{

    /**

    * 吃

    *

    * @param  string $food 食物

    * @return string

    */

    public function eat($food='')

    {

        echo "用叉子吃{$food}~";

    }

}

/**

* 用筷子吃实体

*/

class EatByChopsticks implements EatInterface

{

    /**

    * 吃

    *

    * @param  string $food 食物

    * @return string

    */

    public function eat($food='')

    {

        echo "用筷子吃{$food}~";

    }

}

try {

    // 初始化一个用筷子吃饭的男人的实例

    $male = new PersonMale('male', new EatByChopsticks());

    // 吃饭

    $male->eat('大米');

} catch (Exception $e) {

    echo $e->getMessage();

}

上一篇 下一篇

猜你喜欢

热点阅读