PHP设计模式之适配器模式原理与用法分析
php  /  管理员 发布于 4年前   503
本文实例讲述了PHP设计模式之适配器模式原理与用法。分享给大家供大家参考,具体如下: 一、什么是适配器模式 适配器模式有两种:类适配器模式和对象适配器模式。其中类适配器模式使用继承方式,而对象适配器模式使用组合方式。由于类适配器模式包含双重继承,而PHP并不支持双重继承,所以一般都采取结合继承和实现的方式来模拟双重继承,即继承一个类,同时实现一个接口。类适配器模式很简单,但是与对象适配器模式相比,类适配器模式的灵活性稍弱。采用类适配器模式时,适配器继承被适配者并实现一个接口;采用对象适配器模式时,适配器使用被适配者,并实现一个接口。 二、什么时候使用适配器模式 适配器模式的作用就是解决兼容性问题,如果需要通过适配(使用多重继承或组合)来结合两个不兼容的系统,那就使用适配器模式。 三、类适配器模式 以货币兑换为例: 运行结果: Euros: 72.999 四、对象适配器模式 以桌面环境转向移动环境为例: 更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》 希望本文所述对大家PHP程序设计有所帮助。product = $product; $this->service = $service; $this->dollar = $this->product + $this->service; return $this->requestTotal(); } public function requestTotal() { $this->dollar *= $this->rate; return $this->dollar; }}//欧元计算类class EuroCalc{ private $euro; private $product; private $service; public $rate = 1; public function requestCalc($product,$service) { $this->product = $product; $this->service = $service; $this->euro = $this->product + $this->service; return $this->requestTotal(); } public function requestTotal() { $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();?>
Dollars: $90mobile = $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();?>
您可能感兴趣的文章:
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号