PHP-设计模式-适配器模式

适配器模式:将两个不能直接连接的类(A,B),使用第三个类(C)进行转换。
应用场景:
1:比如,充电器就是个适配器,用来使插线板(两个或三个插孔)和手机(USB接口)连接到一起。
2:比如,不同数据库(mysql,oracle)之间导入表,字段不同,转换成相同的字段。
3:pdo,mysqli等把数据库中的数据转换成PHP 可以使用的数组。

<?php
//手机类   
    class photo{
        //使用usb口进行充电
        static function usbcharge(adapter $adapter){
            $adapter->usbcharge();//适配器中的usb方法
        }
    }
//插线板类
    class lug_plate{
        // a,b方法用来判断是否能插在插线板上。
        function a(){
            //如果是三接口
            return true;
        }
        function b(){
            //如果是两接口
            return true;
        }
        function discharge(){
            if($this->a()||$this->b()){
                echo '正在充电。。。';
            }
        }
    }
//此时的插线板没办法给手机充电,手机只有usb的接口
    class adapter{
        private $plate = null;
        function __construct(){
            $this->plate=new lug_plate;
        }
//在适配器类中把插线板类的方法包装成一个usb充电接口。
        function usbcharge(){
            $this->plate->a();
            $this->plate->b();
            $this->plate->discharge();
        }
    }   
    $c = new photo;
    $d = new adapter;
    $c->charge($d);
?>

猜你喜欢

转载自blog.csdn.net/qq_36211859/article/details/82220374