美文网首页
PHP设计模式-桥接模式

PHP设计模式-桥接模式

作者: 木有sky | 来源:发表于2019-02-17 10:08 被阅读0次

适用性

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

例如:人 => 抽象为属性:性别 动作:吃 => 人吃的动作抽象为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();

}

相关文章

  • PHP设计模式-桥接模式

    适用性 基础的结构型设计模式:将抽象和实现解耦,对抽象的实现是实体行为对接口的实现。 例如:人 => 抽象为属性:...

  • 设计模式-桥接模式

    设计模式-桥接模式 定义 桥接模式(Bridge Pattern)也称为桥梁模式、接口(Interface)模式或...

  • 桥接模式

    设计模式:桥接模式(Bridge)

  • php设计模式之桥接模式

    桥接模式 把抽象化与实现化解耦,使得二者可以独立变化。这种类型的设计模式属于结构型模式,它通过提供抽象化和实现化之...

  • 设计模式——桥接模式

    设计模式——桥接模式 最近公司组件分享设计模式,然而分配给我的是桥接模式。就在这里记录我对桥接模式的理解吧。 定义...

  • 设计模式之桥接模式

    设计模式之桥接模式 1. 模式定义 桥接模式又称柄体模式或接口模式,它是一种结构性模式。桥接模式将抽象部分与实现部...

  • PHP 完整实战23种设计模式

    PHP实战创建型模式 单例模式 工厂模式 抽象工厂模式 原型模式 建造者模式 PHP实战结构型模式 桥接模式 享元...

  • 桥接模式

    介绍 桥接模式(Bridge Pattern) 也称为桥梁模式,是结构型设计模式之一。桥接模式的作用就是连接 "两...

  • Java设计模式——桥接模式

    Java设计模式之桥接模式 回顾 上一期分享了适配器模式,主要为了实现解耦 桥接模式 简介 桥接模式是对象的结构模...

  • 设计模式-桥接模式

    桥接模式介绍 桥接模式(Bridge Pattern)也称为桥梁模式,是结构型设计模式之一。顾名思义其与现实中的桥...

网友评论

      本文标题:PHP设计模式-桥接模式

      本文链接:https://www.haomeiwen.com/subject/rkrieqtx.html