PHP design pattern: adapter pattern code example, php design pattern
Objectives:
The interface of a class can be converted into another interface that the customer wants, so that the originally incompatible interface can work together. A common understanding is to adapt different interfaces to a unified API interface.
Role:
Target is adapted to the Target, which defines the interface for converting other classes, that is, our expected interface.
The Adaptee adapter is the interface to be adapted.
Adapter, the other two roles are existing roles, and the Adapter role needs to be created to adapt the Adaptee to the Target interface.
Application scenarios:
For example, data operations include mysql, mysqli, pdo, sqlite, postgresql, etc. If you need to change the database in the environment generated, you can use the adapter mode to unify the interface. Similarly, the cache scenario is that it is more convenient to change the cache Policy (memcache, redis, apc.
Advantages:
The adapter adapts to the target through the adapter to achieve the goal of being transparent to the customer.
Sample Code:
// Adaptation target. The specified interface will be adapted to the object to implement 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 );
As shown above:
Target adaptation Target: IDataBase Interface
Adaptee adapter: database operation functions of mysql and postgresql
Adapter: mysql and postgresql