我在读一本介绍适配器模式使用的书。它表示,在Web项目中经常使用适配器模式,作为使用数据库API(如PDO或mysqli)而不将页面反复连接到该数据库API的方式。下面是示例代码:不使用适配器接口的适配器模式?
interface DatabaseAdapterInterface
{
function setConnectionInfo($values=array());
function closeConnection();
function runQuery($sql, $parameters=array());
function fetchField($sql, $parameters=array());
function fetchRow($sql, $parameters=array());
function fetchAsArray($sql, $parameters=array());
function insert($tableName, $parameters=array());
function beginTransaction();
function commit();
function rollBack();
//many other methods
}
class DatabaseAdapterPDO implements DatabaseAdapterInterface
{
//implements all the methods in the DatabaseAdapterInterface
}
class DatabaseAdapterMySQLi implements DatabaseAdapterInterface
{
//...implements all the methods in the DatabaseAdapterInterface
}
任何客户端类(或网页),其 需要利用数据库将通过具体的适配器,这样做的:
$connect = array(DBCONNECTION, DBUSER, DBPASS);
$adapter = new DatabaseAdapterPDO($connect);
$sql = 'SELECT * FROM ArtWorks WHERE ArtWorkId=?';
$results = $adapter->runQuery($sql, array(5));
虽然此示例代码中明确包含没有PDO代码,它不完全免费从依赖到我们的数据库API的 。
我明白了,但我不知道为什么我们需要有DatabaseAdapterInterface?我们只需在DatabaseAdapterPDO和DatabaseAdapterMySQLi中定义所有的方法,而无需使用DatabaseAdapterInterface,我们可以节省一些编写DatabaseAdapterInterface的代码,我们可以吗?或者使用DatabaseAdapterInterface可以强制程序员实现所需的方法,以便程序员不会错过任何所需的方法?
'适配器模式经常用于Web项目中,作为利用数据库API(如PDO或mysqli)的一种方式,而不必将页面反复连接到数据库API。“ - 这听起来更像[外墙模式](https://en.wikipedia.org/wiki/Facade_pattern)。你能和我们分享这本书的参考吗? – Fuhrmanator