dsqzhaoyue 发表于 2018-12-17 09:32:45

PHP设计模式 适配器模式

  参考:
  http://www.lai18.com/content/422504.html
  《PHP设计模式》作    者:(美)萨莱   译    者:梁志敏,蔡建
  
  定义:
  适配器设计模式只是将某个对象的接口是适配为另一个对象所期望的接口。
  概述:
  可将一个类的接口转换成客户希望的另外一个接口,使得原本不兼容的接口能够一起工作。通俗的理解就是将不同接口适配成统一的API接口。
  
  角色:
  Target适配目标,该角色定义把其他类转换为何种接口,也就是我们的期望接口。
  Adaptee被适配者,就是需要被适配的接口。
  Adapter适配器,其他的两个角色都是已经存在的角色,而适配器角色是需要新建立的,它用来对Adaptee与Target接口进行适配。
  
  应用场景:
  如数据操作有mysql、mysqli、pdo、sqlite、postgresql等,假若生成环境需要更换数据库时,可利用适配器模式统一接口。
  缓存(cache)的场景也是,这会是更换缓存策略(memcache、redis、apc)更方便。
  错误处理(error)的场景,简单输入bug,记录错误日志
  
  优点:
  1、被适配者通过适配器完成对适配目标的适配,以达到对客户使用透明的目的。
  2、如果使用设配器设计模式,那么绝大部分情况下,不会丢失现有的功能性,只是使用或消耗的方式不同。
  缺点:
  1、过多地使用适配器,会让系统非常零乱,不易整体进行把握。比如,明明看到调用的是 A 接口,其实内部被适配成了 B 接口的实现,一个系统如果太多出现这种情况,无异于一场灾难。因此如果不是很有必要,可以不使用适配器,而是直接对系统进行重构。
  
  示例代码:
  (1)数据库场景
  //适配目标,规定的接口将被适配对象实现

  interface>  public function connect($host, $username, $password, $database);
  public function query($sql);
  }
  //适配器

  class Mysql implements>  protected $connect;
  public function connect($host, $username, $password, $database){
  $connect = mysql_connect($host, $username, $password);
  mysql_select_db($database, $connect);
  $this->connect = $connect;
  //...
  }
  public function query($sql) {
  //...
  }
  }
  //适配器

  class Postgresql implements>  protected $connect;
  public function connect($host, $username, $password, $database) {
  $this->connect = pg_connect("host=$host dbname=$database user=$username password=$password");
  //...
  }
  public function query($sql) {
  //...
  }
  }
  //客户端使用
  $client = new Postgresql();
  $client->query($sql);
  (2)错误处理场景
  //原始错误处理
  class errorObject{
  private $_error;
  public function __construct($error){
  $this->__error = $error;
  }
  public function getError(){
  return $this->__error;
  }
  }
  //通过适配器扩展错误处理
  class logToCsvAdapter extends errorObject{
  private $_errorNumber ,$__errorText;
  public function __construct($error){
  parent::__construct($error);
  $parts = explode(':',$this-getError());
  $this->__errorNumber = $parts;
  $this->__errorText = $parts;
  }
  public function getErrorNumber(){
  return $this->_errorNumber;
  }
  public function getErrorText(){
  return $this->__errorText;
  }
  }

页: [1]
查看完整版本: PHP设计模式 适配器模式