php设计模式课程---8、适配器模式是什么

php设计模式课程---8、适配器模式是什么

一、总结

一句话总结:

充电过程中,手机充电器相对于手机和插座之间就是适配器

1、编程中的适配器是怎么回事?

写一个类(适配器),将传入的数据的格式或者内容修改为需要的,再传出去
例子:而这个类就是相当于手机和插座之间的手机充电器,传入的数据相当于插座上的电,传出的数据相当于给手机充的电
 2 class TianQi {
 3     public function get(){
 4         // 操作API
 5         // 解析XML
 6         // 一系列的复杂操作,得到
 7         return ['temp'=>25.3 , 'wind'=>9.2];
 8     }
 9 }
10 
11 
12 // 到了美国,用华氏度
13 class Us {
14     public function get() {
15         $tq = new TianQi();
16         $row = $tq->get();
17         $row['temp'] = $this->trans( $row['temp'] );
18         
19         return $row;
20     }
21 
22     public function trans($t) {
23         return $t*9/5+32;
24     }
25 }
26 
27 
28 $tq = new TianQi();
29 $us = new Us();
30 
31 print_r($tq->get());
32 print_r($us->get());

2、适配器模式的作用是什么?

将不适合我们使用的数据通过公式或者格式转换成我们能够使用的数据
总结:其实很多处理数据的操作都可以看做是适配器,也就是使这份数据适配了那种情况

3、适配器的操作对象和输出对象是什么?

操作对象:之前操作的结果(或者别人操作的结果)
输出对象:符合需求了的结果

二、适配器模式是什么

1、代码

 1 <?php 
 2 class TianQi {
 3     public function get(){
 4         // 操作API
 5         // 解析XML
 6         // 一系列的复杂操作,得到
 7         return ['temp'=>25.3 , 'wind'=>9.2];
 8     }
 9 }
10 
11 
12 // 到了美国,用华氏度
13 class Us {
14     public function get() {
15         $tq = new TianQi();
16         $row = $tq->get();
17         $row['temp'] = $this->trans( $row['temp'] );
18         
19         return $row;
20     }
21 
22     public function trans($t) {
23         return $t*9/5+32;
24     }
25 }
26 
27 
28 $tq = new TianQi();
29 $us = new Us();
30 
31 print_r($tq->get());
32 print_r($us->get());
33 
34 ?>
 
原文地址:https://www.cnblogs.com/Renyi-Fan/p/9584242.html