PHP design pattern series-adapter. What is an adapter: the adapter design mode only adapts the interface of an object to the interface expected by another object. Design scenario: if we have a UserInfo class, what is the adapter:
The adapter design mode only adapts the interface of an object to the interface expected by another object.
Design scenario:
Assume that we have an original UserInfo class that provides user information. when we design this class early, we only implement one getUserName method to get the user name.
In our MyOldObject class, the user information is obtained from UserInfo and the user name is output.
Over time, our old UserInfo class only provides methods for obtaining user names, which cannot meet the requirements. at the same time, we need to obtain the user's age and other information.
In order not to change the UserInfo class, we inherit UserInfo and create a UserInfoAdapter class to implement the getAge method.
In our new MyNewObject class, we instantiate UserInfoAdapter to print the user name and age.
In this way, with our expansion, we have not changed the original UserInfo class and the interface using this class. we have extended the UserInfo class through the adaptation method.
Code: UserInfo class, implement the getUserName method
[Php]
// An early user class that only implements the method of obtaining the user name
Class UserInfo {
Public function getUserName (){
Return 'initphp ';
}
}
Code: MyOldObject class, which obtains information from the UserInfo class and outputs the 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 the project requirements change over time, the UserInfo class cannot meet the requirements. we have used the UserInfo class adapter to meet the requirements 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. you need to print the user's age and name. The UserInfo class cannot meet your requirements. you need to call the UserInfoAdapter adapter class.
[Php]
Include_once ("UserInfoAdapter. php ");
Class MyNewObject {
Public function write (){
$ UserInfoAdapter = new UserInfoAdapter;
Print_r ($ UserInfoAdapter-> getUser ());
}
}
$ A = new MyNewObject;
$ A-> write ();
Author: initphp
The Ingress adapter design mode only adapts the interface of an object to the interface expected by another object. Design scenario: if we have a UserInfo class, mention...