PHP设计模式之适配器模式

原创
2016/02/12 14:55
阅读数 6
<?php

namespace Tools;

/*
适配器模式
将一个类的接口转换成客户希望的另外一个接口,Adapter模式使得原来由于接口不兼容而不能一起工作的那此类可以一起工作
*/

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

//mysql
class MYSQL implements  IDatabase{
	protected $conn;

	function connect($host,$user,$password,$dbname){
		$conn = mysql_connect($host,$user,$password);
		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);
	}
}

//mysqli
class MYSQLI implements IDatabase{
	protected $conn;

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

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

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

//pdo
class PDO implements  IDatabase{
	protected $conn;

	function connect($host,$user,$password,$dbname){
		$conn = new \PDO("mysql:host=$host;dbname=$dbname",$user,$password);
		$this->conn = $conn;
	}

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

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

//适配器模式
$db = new \Tools\MYSQL();
$db->connect("localhost","root","","test");
$db->query("show tables");
print_r($db);
$db->close();

$db = new \Tools\MYSQLI();
$db->connect("localhost","root","","test");
$db->query("show tables");
print_r($db);
$db->close();

$db = new \Tools\PDO();
$db->connect("localhost","root","","test");
$db->query("show tables");
print_r($db);
$db->close();



展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
1
分享
返回顶部
顶部