php桥接模式

博客介绍了结构型模式中的PHP桥接模式,它是基础的结构型设计模式,核心是将抽象和实现解耦,抽象的实现是实体行为对接口的实现,还举例说明,如将人抽象出属性和动作,把人吃的动作抽象为接口并实现不同吃法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 结构型模式

 php桥接模式
 基础的结构型设计模式:将抽象和实现解耦,对抽象的实现是实体行为对接口的实现
 例如:人 => 抽象为属性:性别 动作:吃 => 人吃的动作抽象为interface => 实现不同的吃法

<?php
namespace bridge;

/**
 * 吃接口
 */
interface EatInterface
{
  /**
   * 吃
   *
   * @param  string $food 食物
   * @return mixed
   */
  public function eat($food='');
}
<?php
namespace bridge;

/**
 * 用筷子吃实体
 */
class EatByChopsticks implements EatInterface
{
  /**
   * 吃
   *
   * @param  string $food 食物
   * @return string
   */
  public function eat($food='')
  {
    echo "用筷子吃{$food}~";
  }
}
<?php
namespace bridge;

/**
 * 用叉子吃实体
 */
class EatByFork implements EatInterface
{
  /**
   * 吃
   *
   * @param  string $food 食物
   * @return string
   */
  public function eat($food='')
  {
    echo "用叉子吃{$food}~";
  }
}
<?php
namespace bridge;

/**
 * 人抽象类
 */
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='');
}
<?php
namespace bridge;

/**
 * 男人实类
 */
class PersonMale extends PersonAbstract
{
  /**
   * 吃的具体方式
   *
   * @param  string $food 食物
   * @return string
   */
  public function eat($food='')
  {
    $this->_tool->eat($food);
  }
}
<?php
/**
 * 结构型模式
 *
 * php桥接模式
 * 基础的结构型设计模式:将抽象和实现解耦,对抽象的实现是实体行为对接口的实现
 * 例如:人 => 抽象为属性:性别 动作:吃 => 人吃的动作抽象为interface => 实现不同的吃法
 *
 *   
 * @example 运行 php test.php
 */


// 注册自加载
spl_autoload_register('autoload');

function autoload($class)
{
  require dirname($_SERVER['SCRIPT_FILENAME']) . '//..//' . str_replace('\\', '/', $class) . '.php';
}

/************************************* test *************************************/

use bridge\PersonMale;
use bridge\EatByChopsticks;
use bridge\EatByFork;

try {
  // 初始化一个用筷子吃饭的男人的实例
  $male = new PersonMale('male', new EatByChopsticks());
  // 吃饭
  $male->eat('大盘鸡');

} catch (\Exception $e) {
  echo $e->getMessage();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

韩淼燃

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值