目的
为了适配不同的接口,将一个类的接口转换成可应用的兼容接口,或者是解决现有类中方法名与目标类中方法名定义不一样导致接口无法使用
角色
- Adapter适配器:包装不兼容接口的对象
- Adaptee适配者:适配的类
应用场景
- 客户端的数据库适配器
例子——不同数据库连接
适配器Database.php
<?php
/**
* Created by PhpStorm.
* User: 何晓宏
* Date: 2018/9/30
* Time: 0:42
*/
namespace AdapterPattern;
interface Database{
function connect($host, $user, $passwd, $db);
function query($sql);
function close();
}
适配者MySQL.php
<?php
/**
* Created by PhpStorm.
* User: 何晓宏
* Date: 2018/9/30
* Time: 0:41
*/
namespace AdapterPattern;
class MySQL implements Database{
protected $conn;
function connect($host, $user, $passwd, $db)
{
$conn =mysql_connect($host,$user,$passwd);
mysql_select_db($db,$conn);
$this->conn=$conn;
}
function query($sql)
{
$result= mysql_query($sql,$this->conn);
return $result;
}
function close()
{
mysql_close($this->conn);
}
}
适配者 MySQLi.php
<?php
/**
* Created by PhpStorm.
* User: 何晓宏
* Date: 2018/9/30
* Time: 0:42
*/
namespace AdapterPattern;
class MySQLi implements Database{
protected $conn;
function connect($host, $user, $passwd, $db)
{
$conn=mysqli_connect($host, $user, $passwd, $db);
$this->conn=$conn;
}
function query($sql)
{
return mysqli_query($this->conn,$sql);
}
function close()
{
mysqli_close($this->conn);
}
}
适配者 PDO.php
<?php
/**
* Created by PhpStorm.
* User: 何晓宏
* Date: 2018/9/30
* Time: 0:42
*/
namespace AdapterPattern;
class PDO implements Database{
protected $conn;
function connect($host, $user, $passwd, $db)
{
$conn=new \PDO("mysql:host=$host; dbname=$db" ,$user,$passwd);
$this->conn=$conn;
}
function query($sql)
{
return $this->conn->query($sql);
}
function close()
{
unset($this->conn);
}
}
$db1=new AdapterPattern\MySQLi();
$db1->connect('127.0.0.1','root','','');
$db1->query("show databases");
$db1->close();
$db2=new AdapterPattern\MySQL();
$db2->connect('127.0.0.1','root','','');
$db2->query("show databases");
$db2->close();
$db3=new AdapterPattern\PDO();
$db3->connect('127.0.0.1','root','','');
$db3->query("show databases");
$db3->close();
优点
- 将目标类与适配者类解耦
- 符合开闭原则,具有良好的灵活性和扩展性,可以不修改原有代码增加新的适配者类
- 类的封装在适配者中,增加了类的透明性和复用性