您的位置:首页 > 编程语言 > PHP开发

PHP设计模式之适配器模式原理与用法分析

2019-01-09 16:33 921 查看

来源:http://news.mkq.online/ 作者:牛站新闻

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

一、什么是适配器模式

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

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

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

三、类适配器模式

以货币兑换为例:
01

<?php 02 /** 03 类适配器模式 04 以货币兑换为例 05 */ 06 //美元计算类 07 class DollarCalc 08 { 09 private $dollar; 10 private $product; 11 private $service; 12 public $rate = 1; 13 public function requestCalc($product,$service) 14 { 15 $this->product = $product; 16 $this->service = $service; 17 $this->dollar = $this->product + $this->service; 18 return $this->requestTotal(); 19 } 20 public function requestTotal() 21 { 22 $this->dollar = $this->rate; 23 return $this->dollar; 24 } 25 } 26 //欧元计算类 27 class EuroCalc 28 { 29 private $euro; 30 private $product; 31 private $service; 32 public $rate = 1; 33 public function requestCalc($product,$service) 34 { 35 $this->product = $product; 36 $this->service = $service; 37 $this->euro = $this->product + $this->service; 38 return $this->requestTotal(); 39 } 40 public function requestTotal() 41 { 42 $this->euro *= $this->rate; 43 return $this->euro; 44 } 45 } 46 //欧元适配器接口 47 interface ITarget 48 { 49 function requester(); 50 } 51 //欧元适配器实现 52 class EuroAdapter extends EuroCalc implements ITarget 53 { 54 public function construct() 55 { 56 $this->requester(); 57 } 58 function requester() 59 { 60 $this->rate = .8111; 61 return $this->rate; 62 } 63 } 64 //客户类 65 class Client 66 { 67 private $euroRequest; 68 private $dollarRequest; 69 public function construct() 70 { 71 $this->euroRequest = new EuroAdapter(); 72 $this->dollarRequest = new DollarCalc(); 73 $euro = "
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: