适配器模式,可以将截然不同的函数接口封装成统一的API;
应用举例,PHP的数据库操作有Mysql、Mysqli、pdo三种,可以用适配器模式统一成一致,类似的场景还有cache适配器,将memcache、redis,file,apc等不同的缓存函数统一成一致。
IDatabase.php
<?phpnamespace Baobab;interface IDatabase{ function connect($host, $user, $passwd, $dbname); function query($sql); function fetch_result($result); function close();}
Mysqli.php
<?phpnamespace BaobabDatabase;use BaobabIDatabase;class Mysqli implements IDatabase{ protected $conn; function connect($host, $user, $passwd, $dbname){ $conn = mysqli_connect($host, $user, $passwd, $dbname); mysqli_set_charset($conn, 'utf8'); $this->conn = $conn; } function query($sql) { return mysqli_query($this->conn, $sql); } function fetch_result($result){ return mysqli_fetch_all($result); } function close() { mysqli_close($this->conn); }}
Pdo.php
<?phpnamespace BaobabDatabase;use BaobabIDatabase;class Pdo implements IDatabase{ protected $conn; function connect($host, $user, $passwd, $dbname){ $conn = new PDO("mysql:dbname=$dbname;host=$host", $user, $passwd); $this->conn = $conn; } function query($sql){ return $this->conn->query($sql); } function fetch_result($result){ } function close() { unset($this->conn); }}
index.php
$db = new BaobabDatabaseMysqli();$db->connect('127.0.0.1', 'root', '', 'test');$res = $db->query('select * from ha_cl');print_r($db->fetch_result($res));$db->close();
还可以参考 http://www.phppan.com/2010/07/php-design-pattern-10-adapter/