This article mainly introduces the Adapter mode code example of PHP design mode. This article describes the objectives, roles, application scenarios, advantages, and other content, and provides code examples. For more information, see
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