• 程序设计模式之适配器模式(php)


    适配器模式(adapter)

    适配器模式,属于结构性模式中最简单的模式之一,主要的作用就是将原本不通用的接口或者方法,通过中间层的转换使其使用于新的需求,说白了就算我们从来没有学习过设计模式,遇到这种问题也能轻松的解决掉,只不过别人给起了一个高大上的名字而已

    例子

    现在我们用php写了一个活动天气的接口,这个接口里面返回的数据使用serialize进行了序列化处理,本来其他客户端获取数据后再使用反序列化处理就完全没有问题,但是过一段时间后我们增加了一个使用go语言开发的客户端也要使用这个天气接口,但是go语言没法跟php一样使用反序列化解析数据就导致数据不兼容的问题出现,这时候就可以使用适配器模式来解决我们的问题

    viewcode
    
    /**
     * 定义天气类,获取天气
     * Class Weather
     */
    class Weather
    {
        /**
         * 获取天气
         */
        public function getWeather()
        {
            $weather = [
                'temp' => '18',
                'hum' => '20%',
                'wea' => '多云'
            ];
    
            return serialize($weather);
        }
    }
    
    /**
     * 定义天气适配器接口
     * Interface WeatherAdapter
     */
    interface WeatherAdapter
    {
        public function __construct(Weather $weather);
    
        public function getWeather();
    }
    
    /**
     * 定义go程序获取天气的类,这个类实现了天气适配器,所以go客户端只需要调用这个类就可以获取到go能解析的数据了
     * Class GoWeather
     */
    class GoWeather implements WeatherAdapter
    {
    
        private $weather;
    
        public function __construct(Weather $weather)
        {
            $this->weather = $weather;
        }
    
        public function getWeather()
        {
            // TODO: Implement getWeather() method.
            $data = $this->weather->getWeather();
            $data = unserialize($data);
            return json_encode($data, 256);
        }
    }
    
    
    //客户端调用
    $goWeather = new GoWeather(new Weather());
    echo $goWeather ->getWeather();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
  • 相关阅读:
    【springboot+vue】原生小程序电子班牌系统 智慧校园云平台源码
    物联网,智慧城市的数字化转型引擎
    2016 ZCTF note3:一种新解法
    Vue / Vue指令、事件修饰符、事件参数
    Java——JDK1.8新特性
    如何解决前端上线之后用户页面不刷新的问题
    Go 消息队列及工作池处理
    经典递归回溯问题之——解数独(LeetCode 37)
    springboot学生综合素质测评系统java
    K8S入门前奏之VMware虚拟机网络配置
  • 原文地址:https://blog.csdn.net/weixin_44540711/article/details/127416656