设计模式之适配器

来源:互联网 发布:mac的文件夹在哪里 编辑:程序博客网 时间:2024/05/17 07:19

模式定义

当我们引用一个第三方类库,这个类库随着版本的改变,它提供的API也可能会改变。如果很不幸的是,你的应用里引用的某个API已经发生改变的时候,除了在心中默默地骂“wocao”之外,你还得去硬着头皮去改大量的代码。

适配器模式将一个类的换成客户端需要的另一个接口,使原本不兼容的接口能一起工作

在应用中,适配器模式分为类适配器和对象适配器

Target适配目标,该角色定义把其他类转换为何种接口,也就是我们的期望接口。
Adaptee被适配者,就是需要被适配的接口。
Adapter适配器,其他的两个角色都是已经存在的角色,而适配器角色是需要新建立的,它用来对Adaptee与Target接口进行适配。

类适配器

类适配器中适配器继承原有的Adaptee类,自己实现原类没有的操作。

模式结构

类适配器

代码分析

<?phpinterface ITarget{      function operation1();      function operation2();  }  interface IAdaptee{      function operation1();  }  class Adaptee extends IAdaptee{      public  function operation1(){          echo "原方法";      }  }  class Adapter extends Adaptee implements IAdaptee, ITarget{      public  function operation2(){          echo "适配方法";      }  }  class Client{      public  function test(){          $adapter = new Adapter();          $adapter->operation1();    //原方法          $adapter->operation2();    //适配方法      }  }  ?>

对象适配器

类适配器使用的是继承模式,而对象适配器使用的是组合模式,将adaptee作为adapter的一个引用。

模式结构

对象适配器

代码分析

<?phpinterface ITarget{      function operation1();      function operation2();  }  interface IAdaptee{      function operation1();  }  class Adaptee extends IAdaptee{      public  function operation1(){          echo "原方法";      }  }  class Adapter implements  ITarget{      private $adaptee;      public function __construct($adaptee){          $this->adaptee = $adaptee;      }      public  function operation1(){           return $this->adaptee->operation1();      }      public  function operation2(){          echo "适配方法";      }  }  class Client{      public  function test(){          $adapter = new Adapter(new Adaptee(null));          $adapter->operation1();     //原方法          $adapter->operation2();     //适配方法      }  }  ?>

由于组合在耦合性上小于继承,对象适配器显得更加灵活,当然它的缺点是增加代码量。 需要重写adapee中的方法的数量太大的话,可以考虑在adapter中使用__call方法委托adapee取得客户端调用的方法.

<?phppublic function __call($func, $args){      if (is_callable(array($this->adaptee, $func))) {          return $this->adaptee->$func($args);      }      trigger_error('*********', E_USER_ERROR);  }  ?>

总结

将一个类的接口转换成客户希望的另外一个接口,使用原本不兼容的而不能在一起工作的那些类可以在一起工作.

把对某些相似的类的操作转化为一个统一的“接口”(这里是比喻的说话)–适配器,或者比喻为一个“界面”,统一或屏蔽了那些类的细节。适配器模式还构造了一种“机制”,使“适配”的类可以很容易的增减,而不用修改与适配器交互的代码,符合“减少代码间耦合”的设计原则。

0 0