适配器模式

来源:互联网 发布:淘宝怎么看自己的淘龄 编辑:程序博客网 时间:2024/04/30 11:03

–参考书籍《php设计模式》
当外部API库改变时,如何让使用者动态的升级?
运用适配器(Adapter)模式来避免因外部库改变所带来的不便。

如向上兼容举例:
使用者版本1-hello ——> 最新库的-haoo(库版本1时,是hello方法)
使用者版本2-greet ——> 最新库的-haoo(库版本2时,hello方法消失,变成greet方法)
使用者版本3-haoo ——> 最新库的-haoo(版本库3时,greet方法也消失,变成haoo方法)

<?php//version1/*class HwLib { function hello(){     return 'Hello '; }  function world() {     return 'World!'; }}$s = new HwLib;echo $s->hello(),$s->world();*/// version 2/*class HwLib { //此时库的greet完全替代了hello,使用库的代码也必须做出相应的改变,问题:如何才能让使用者不变呢? function greet(){     return 'Greetings and Salutations '; } function world() {     return 'World!'."\n"; }}*/// version 3class HwLib { //此时库的haoo完全替代了greet function haoo(){     return 'haoo++++++++ '; } function world() {     return 'World!'."\n"; }}/*组合的方式实现适配器*/class HwLibV2ToV1Adapter{ var$libv2; function HwLibV2ToV1Adapter(&$libv2) {     $this->libv2 = &$libv2; } function hello(){     return $this->libv2->greet(); } function world() {     return $this->libv2->world(); } }class HwLibV3ToV2Adapter{ var$libv3; function HwLibV3ToV2Adapter(&$libv3) {     $this->libv3 = &$libv3; } function greet(){     return $this->libv3->haoo(); } function world() {     return $this->libv3->world(); } }//工厂模式生成function & HwLibInstance($ver='') { switch ($ver) { case 'V3':     return new HwLib; case 'V2':     return new HwLibV3ToV2Adapter(new HwLib);  default:     return new HwLibV2ToV1Adapter(new HwLibV3ToV2Adapter(new HwLib)); }} $s = HwLibInstance('V1');echo $s->hello(),$s->world();$s = HwLibInstance('V2');echo $s->greet(),$s->world();$s = HwLibInstance('V3');echo $s->haoo(),$s->world();//通过继承实现适配器class HwLibGofV2ToV1Adapter extends HwLib{  function hello(){     return parent::greet(); } }class HwLibGofV3ToV2Adapter extends HwLibGofV2ToV1Adapter{ function hello(){     return parent::haoo(); }  function greet(){ //return parent::haoo();     return $this->haoo(); }}//工厂模式生成function & HwLibInstanceGof($ver='') {      return new HwLibGofV3ToV2Adapter;}$s = HwLibInstanceGof('V1');echo $s->hello(),$s->world();$s = HwLibInstanceGof('V2');echo $s->greet(),$s->world();$s = HwLibInstanceGof('V3');echo $s->haoo(),$s->world();
0 0
原创粉丝点击