• 适配模式


    定义:可以将截然不同的函数接口封装成统一的API
    实际应用举例:1.PHP的数据库有mysql,mysqli,pdo3种,可以用适配器模式统一成一致
                            2.cache适配器,将memcache,redis,file,apc等不同的缓存函数,统一成一致

    以实际应用举例1作为示例
    $db = new IMoocDatabaseMySQL();
    //$db = new IMoocDatabaseMySQLi();
    //$db = new IMoocDatabasePDO();
    $db->connect('127.0.0.1', 'root', 'root', 'test');
    $db->query("show databases");
    $db->close();

    <?php
    namespace IMooc;

    interface IDatabase
    {
    function connect($host, $user, $passwd, $dbname);
    function query($sql);
    function close();
    }

    <?php
    namespace IMoocDatabase;

    use IMoocIDatabase;

    class MySQL implements IDatabase
    {
    protected $conn;
    function connect($host, $user, $passwd, $dbname)
    {
    $conn = mysql_connect($host, $user, $passwd);
    mysql_select_db($dbname, $conn);
    $this->conn = $conn;
    }

    function query($sql)
    {
    $res = mysql_query($sql, $this->conn);
    return $res;
    }

    function close()
    {
    mysql_close($this->conn);
    }
    }

    <?php
    namespace IMoocDatabase;

    use IMoocIDatabase;

    class MySQLi implements IDatabase
    {
    protected $conn;

    function connect($host, $user, $passwd, $dbname)
    {
    $conn = mysqli_connect($host,$user,$passwd,$dbname);
    $this->conn = $conn;
    }

    function query($sql)
    {
    return mysqli_query($this->conn, $sql);
    }

    function close()
    {
    mysqli_close($this->conn);
    }
    }

    <?php
    namespace IMoocDatabase;

    use IMoocIDatabase;

    class PDO implements IDatabase
    {
    protected $conn;
    function connect($host, $user, $passwd, $dbname)
    {
    $conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $passwd);
    $this->conn = $conn;
    }

    function query($sql)
    {
    return $this->conn->query($sql);
    }

    function close()
    {
    unset($this->conn);
    }
    }

     





  • 相关阅读:
    t讯src的一点小秘密
    SQL注入科普
    U盘,移动硬盘显示显示需要格式化怎么修复
    Linux提高工作效率的命令
    SpringBoot配置文件加载位置与优先级
    如何选择分布式事务形态(TCC,SAGA,2PC,基于消息最终一致性等等)
    Java IO总结
    Java并发编程指南
    Linux下的crontab定时执行任务命令详解
    Zookeeper的功能以及工作原理
  • 原文地址:https://www.cnblogs.com/phonecom/p/045f3d736d4c8a29c10b32149f9d94f8.html
Copyright © 2020-2023  润新知