1.适配器模式:
可以将截然不同的函数接口封装成统一的API
2.实际应用举例,PHP的数据库操作有mysql, mysqli, pdo3种,可以用适配器模式统一成一致。类似的场景还有cache适配器,就是将memcache,redis,file,apc等不同的缓存函数统一成一致的
3.下面的例子可以帮助你对付各种数据库链接功能,mysql mysqli, pdo随便选,操作都抽象为统一的接口客户端不需要修改一行数据库链接方式
interface IDatabase
{
function connect($host, $user, $passwd, $dbname);
function query($sql);
function close();
}
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);
}
}
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);
}
}
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);
}
}
$db = new PDO();
$db->connect(‘127.0.0.1‘, ‘root‘, ‘root‘, ‘test‘);
$db->query(‘show databases‘);
$db->close();
$db = MySQLi ();
$db->connect(‘127.0.0.1‘, ‘root‘, ‘root‘, ‘test‘);
$db->query(‘show databases‘);
$db->close();
$db = MySQl PDO();
$db->connect(‘127.0.0.1‘, ‘root‘, ‘root‘, ‘test‘);
$db->query(‘show databases‘);
$db->close();
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/wjc19911118/article/details/46849751