Home > Article > Backend Development > A brief analysis of php adapter mode (Adapter), a brief analysis of adapter_PHP tutorial
The previous articles introduced the characteristics of design patterns and explained in detail the four creational patterns. The creational pattern is responsible for how to generate object instances. Next, we will talk about the structural pattern.
1. What is a structural pattern?
Structural pattern is to analyze the internal structure and external combination of classes and objects, and solve the coupling problem between modules by optimizing the program structure.
2. Types of structural patterns :
Adapter Mode
Bridge Mode
Decoration Mode
Combination mode
Appearance Mode
Flyweight mode
Proxy mode
1. Adapter mode (Adapter)
By converting the interface of a class into another interface that the client wants, the adapter pattern enables classes that originally could not work together due to incompatible interfaces to work together.
Application scenarios: The old code interface does not meet the new interface requirements, or the code is too messy to continue to modify, or a third-party class library is used.
Code implementation
Function getUserName();
}
class UserInfo implements UserInterface {
protected $user;
Function __construct($user) {
$this->user = $user;
}
Public function getUserName() {
return $this->user->getName();
}
}
$olduser = new User('Zhang San');
echo $olduser->getName()."n";
$newuser = new UserInfo($olduser);
Note: The new interface here uses the combination method. There is a member variable inside UserInfo to save the old interface User object. The modules are loosely coupled. This structure is actually the combination mode. Do not use inheritance. Although UserInfo can achieve the same purpose by inheriting User, the coupling is high and they will affect each other.
http://www.bkjia.com/PHPjc/917026.html
www.bkjia.com