PHP design mode-adapter Mode
The adapter mode (sometimes called the packaging style or packaging) adapts the interface of a class to what the user expects (the core issue to be solved by the adapter mode ). An adaptation allows a class that cannot work together because the interface is not compatible, by encapsulating its own interface in an existing class.
Class diagram:
ForeignPlayer role: the interface rules of this role are inconsistent, but the method function of this role must be called internally.
Internal interface (IPlayer) Role: This is an abstract role that provides internal interface rules that are expected.
Adapter role: Wrap an Adapter object internally to convert the interface to be adapted to the target interface. This role is the core role in the Adapter mode, it is also the key to the problem solved by the adapter mode.
Code:
;} Function Defense () {echo forward Defense;}/** Center * Class Center */class Center implements IPlayer {function Attack () {echo Center Attack ;} function Defense () {echo center Defense; }}// -------------- target audience -----------/** Yao Ming foreign athlete * Class Yaoming */class Yaoming {function attack () {echo Yao Ming attack;} function defense () {echo Yao Ming defense ;}} // ------------ Adapter --------------/** Adapter * Class Adapter */class Adapter implements IPlayer {private $ _ player; function _ construct () {$ this-> _ player = new Yaoming ();} function Attack () {$ this-> _ player-> Attack ();} function Defense () {$ this-> _ player-> defense ();}}
Client test code:
Header (Content-Type: text/html; charset = UTF-8); // ------------------------ prototype mode test code ------------------ require_once. /Adapter. php; $ player1 = new Forward (); echo Forward:; $ player1-> Attack (); $ player1-> Defense (); echo
Echo Yao Ming:
; $ Yaoming = new Adapter (); $ yaoming-> Attack (); $ yaoming-> Defense ();
Applicable scenarios
1. All methods to be implemented are specified in the interface
2. But there must be a specific class that implements this interface. Only a few of the methods are used, and other methods are useless.
Notes
1. The class that acts as the adapter is the abstract class that implements the existing interface
2. Why use abstract classes:
This class should not be instantiated. Acting only as an adapter provides a common interface for its sub-classes, but its sub-classes can focus only on areas of interest.