Translate the interface of a class into another interface that the customer wants. The Adapter pattern enables classes to work together that would otherwise not work together due to interface incompatibilities

Target role: defines the domain-specific interface used by the client, which is what we expect to get the source (Adaptee) role: Adaptee role: Adaptee interface to Target interface; The adapter is the core of this pattern. The adapter converts the source interface into the target interface. This role is applicable to specific classes. 3. You want to use an existing subclass, but it is not possible to subclass each one to match their interfaces. Object adapters can be adapted to their superclass interfaces (object adapters only)

In practice, the adapter pattern is divided into class adapter and object adapter

Class 1 adapter

Interface ITarget {function operation1(); function operation2(); } // Source role interface IAdaptee {function operation1(); } class Adaptee implements IAdaptee {public function operation1() {echo "implements "; Class Adapter extends Adaptee implements IAdaptee, ITarget {public function operation2() {echo "Adaptee "; } } class Client { public function test() { $adapter = new Adapter(); $adapter->operation1(); $adapter->operation2(); // Match method}}Copy the code

1 Object Adapter

Interface ITarget {function operation1(); function operation2(); } // Source role interface IAdaptee {function operation1(); } class Adaptee implements IAdaptee {public function operation1() {echo "implements "; Class Adapter implements ITarget {private $adaptee; public function __construct($adaptee) { $this->adaptee = $adaptee; } public function operation1() { return $this->adaptee->operation1(); } public function operation2() {echo "operation2 "; } } class Client { public function test() { $adapter = new Adapter(new Adaptee(null)); $adapter->operation1(); $adapter->operation2(); // Match method}}Copy the code

In a class adapter, the adapter inherits the original Adaptee class and implements operations that the original class does not, using the inheritance pattern, while the object adapter uses the composite pattern, using the Adaptee as a reference to adapter. Because composition is less coupled than inheritance, object adapters are more flexible but have the disadvantage of increasing the amount of code. If the number of methods in adapee that need to be overridden becomes too large, consider adding a __call method to the Adapter class that delegates the adapee to get the methods called by the client

public function __call($func, $args)  
{  
    if (is_callable(array($this->adaptee, $func))) {  
        return $this->adaptee->$func($args);  
    }  
    trigger_error('*********', E_USER_ERROR);  
}Copy the code