PHP   发布时间:2019-11-10  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了PHP设计模式之适配器模式原理与用法分析大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

本文实例讲述了php设计模式之适配器模式原理与用法。分享给大家供大家参,具体如下:

一、什么是适配器模式

适配器模式有两种:类适配器模式和对象适配器模式。其中类适配器模式使用继承方式,而对象适配器模式使用组合方式。由于类适配器模式包含双重继承,而php并不支持双重继承,所以一般都采取结合继承和实现的方式来模拟双重继承,即继承一个类,同时实现一个接口。类适配器模式很简单,但是与对象适配器模式相比,类适配器模式的灵活性稍弱。采用类适配器模式时,适配器继承被适配者并实现一个接口;采用对象适配器模式时,适配器使用被适配者,并实现一个接口。

二、什么时候使用适配器模式

适配器模式的作用就是解决兼容性问题,如果需要通过适配(使用多重继承或组合)来结合两个不兼容的系统,那就使用适配器模式。

三、类适配器模式

以货币兑换为例:

php;"> product = $product; $this->@R_489_9260@ce = $@R_489_9260@ce; $this->dollar = $this->product + $this->@R_489_9260@ce; return $this->request@R_877_10586@l(); } public function request@R_877_10586@l() { $this->dollar *= $this->rate; return $this->dollar; } } //欧元计算类 class EuroCalc { private $euro; private $product; private $@R_489_9260@ce; public $rate = 1; public function requestCalc($product,$@R_489_9260@cE) { $this->product = $product; $this->@R_489_9260@ce = $@R_489_9260@ce; $this->euro = $this->product + $this->@R_489_9260@ce; return $this->request@R_877_10586@l(); } public function request@R_877_10586@l() { $this->euro *= $this->rate; return $this->euro; } } //欧元适配器接口 interface ITarget { function requester(); } //欧元适配器实现 class Euroadapter extends EuroCalc implements ITarget { public function __construct() { $this->requester(); } function requester() { $this->rate = .8111; return $this->rate; } } //客户类 class Client { private $eurorequest; private $dollarrequest; public function __construct() { $this->eurorequest = new Euroadapter(); $this->dollarrequest = new DollarCalc(); $euro = "€"; echo "Euros: $euro" . $this->makeAdapterrequest($this->eurorequest) . "
"; echo "Dollars: $" . $this->makeDollarrequest($this->dollarrequest); } private function makeAdapterrequest(ITarget $req) { return $req->requestCalc(40,50); } private function makeDollarrequest(DollarCalc $req) { return $req->requestCalc(40,50); } } $client = new Client(); ?>

运行结果:

四、对象适配器模式

以桌面环境转向移动环境为例:

php;"> @H_718_32@mobile = $mobile; } public function formatCSS() { $this->mobile->formatCSS(); } public function formatGraphics() { $this->mobile->formatGraphics(); } public function horizontalLayout() { $this->mobile->verticalLayout(); } } //客户类 class Client { private $mobile; private $mobileAdapter; public function __construct() { $this->mobile = new Mobile(); $this->mobileAdapter = new MobileAdapter($this->mobilE); $this->mobileAdapter->formatCSS(); $this->mobileAdapter->formatGraphics(); $this->mobileAdapter->horizontalLayout(); } } $client = new Client(); ?>

更多关于php相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》、《》及《php常见数据库操作技巧汇总》

希望本文所述对大家php程序设计有所帮助。

大佬总结

以上是大佬教程为你收集整理的PHP设计模式之适配器模式原理与用法分析全部内容,希望文章能够帮你解决PHP设计模式之适配器模式原理与用法分析所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。