php桥接模式

64 阅读1分钟

 结构型模式

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();
}