What is an adapter:
The adapter design pattern simply adapts the interface of one object to the interface expected by another object.
Design scenario:
Suppose we originally had a UserInfo class, a class that provides user information. When we designed this class early on, we only implemented a getUserName method to obtain the user name.
In our MyOldObject class, we will obtain user information from the UserInfo class and output the user name
As time goes by, our old UserInfo class only provides a method to obtain the user name, which can no longer meet the needs. We also need to obtain the user's age and other information.
In order not to change the original UserInfo class, we inherit UserInfo, create a UserInfoAdapter class, and implement methods such as getAge to obtain age.
In our new MyNewObject class, we instantiate the UserInfoAdapter and print out the user's name and age.
In this way, as we expand, we do not change the original UserInfo class and the interface that uses this class. We extend the UserInfo class through the adaptation method
Code: UserInfo class, implements getUserName method
[php]
//An early user class only implemented the method of obtaining the user name
class UserInfo {
Public function getUserName() {
return 'initphp';
}
}
Code: MyOldObject class, obtain information from UserInfo class, output user name
[php]
include_once("UserInfo.php");
class MyOldObject {
Public function write() {
$UserInfo = new UserInfo;
echo $UserInfo->getUserName();
}
}
$a = new MyOldObject;
$a->write();
Code: UserInfoAdapter class. As time goes by, project requirements are changing and the UserInfo class cannot meet the needs. We have made an adapter for the UserInfo class to meet the needs of new functions
[php]
include_once("UserInfo.php");
class UserInfoAdapter extends UserInfo{
Public function getUserAge() {
Return 28;
}
Public function getUser() {
return array(
'username' => $this->getUserName(),
'age' => $this->getUserAge()
);
}
}
Code: MyNewObject class, a new function class, needs to print out the user’s age and name. The UserInfo class cannot meet the needs, and the UserInfoAdapter adapter class needs to be called
[php]
include_once("UserInfoAdapter.php");
class MyNewObject {
Public function write() {
$UserInfoAdapter = new UserInfoAdapter;
print_r($UserInfoAdapter->getUser());
}
}
$a = new MyNewObject;
$a->write();
Author: initphp