Goal:
The interface of one class can be converted into another interface that the client wants, so that an otherwise incompatible interface can work together. A popular understanding is to adapt different interfaces to a unified API interface.
Role:
Target matches the goal, which defines the interface to which other classes are converted, which is our desired interface.
Adaptee is adapted to the interface that needs to be fitted.
Adapter adapters, the other two roles are already existing roles, and the adapter role needs to be created to match the adaptee to the target interface.
Application Scenario:
If the data operation has MySQL, Mysqli, PDO, SQLite, PostgreSQL, etc., if the generation environment needs to replace the database, you can use the adapter mode unified interface. Also in the same cache scenario, this would be more convenient to replace the caching policy (memcache, Redis, APC).
Advantage:
The adapter completes the suitability of the matching target through the adaptor, in order to achieve the purpose of transparent use of the customer.
Sample code:
Adaptation targets, the specified interface will be implemented by the adapter object
interface idatabase
{public
function connect ($host, $username, $password, $ database);
Public Function query ($sql);
Adapter
class Mysql implements Idatabase
{
protected $connect;
Public function Connect ($host, $username, $password, $database)
{
$connect = mysql_connect ($host, $username, $password);
mysql_select_db ($database, $connect);
$this->connect = $connect;
//...
}
Public Function Query ($sql)
{
//...
}
}
Adapter
class Postgresql implements Idatabase
{
protected $connect;
Public function Connect ($host, $username, $password, $database)
{
$this->connect = Pg_connect ("host=$ Host dbname= $database user= $username password= $password ");
//...
}
Public Function Query ($sql)
{
//...
}
}
The client uses
$client = new Postgresql ();
$client->query ($sql);
Above
Target matching target: Idatabase interface
Adaptee: MySQL and PostgreSQL database operations functions
Adapter adapters: MySQL classes and PostgreSQL classes