The adapter design pattern simply fits an interface of an object to the interface expected by another object.
- If we primitive have a userinfo class, provide the class of user information, get up early to design this class, only implement a method that GetUserName obtains the user name.
- In our Myoldobject class, the user information is obtained from the UserInfo class, and the user name is output
- Over time, our old userinfo This class only provides the method to obtain the user name, has not been able to satisfy the demand, we also need to obtain the user's age and so on information.
- In order not to change the original userinfo this class, we inherit UserInfo, build a Userinfoadapter class, achieve getage get age such method.
- In our mynewobject new class, we instantiate Userinfoadapter and print out the name and age of the user.
- Thus, with our expansion, we did not change the original userinfo this class and use the interface of this class, we extend the UserInfo class by the method of adaptation
- Code: UserInfo class, implementing the GetUserName method
<? PHP // an early user class that only implements methods to get the user name class UserInfo { publicfunction getusername () { return ' Initphp '; } }
Code: Myoldobject class, obtaining information from the UserInfo class, outputting the user name
<? php include_once ("userinfo.php" class Myoldobject { public function write () { Span style= "color: #800080;" > $UserInfo = new UserInfo; echo $UserInfo ->getusername (); }} $a = new Myoldobject; $a ->write ();
Code: Userinfoadapter class, Over time, the project needs are changing, UserInfo class can not meet the requirements, we do the UserInfo class adapter, to meet the needs of new features
<?PHPinclude_once("userinfo.php"); classUserinfoadapterextendsuserinfo{ Public functionGetuserage () {return28; } Public functionGetUser () {return Array( ' Username ' =$this->getusername (), ' age ' =$this-getuserage ()); } }
Code: MyNewObject class, New function class, need to print out user age and name, UserInfo class can not meet the requirements, need to call Userinfoadapter adapter this class
<? PHP include_once ("userinfoadapter.php"); class MyNewObject { publicfunction write () { $UserInfoAdapter New Userinfoadapter; Print_r ($UserInfoAdapter-GetUser ()); } } $a New mynewobject; $a
Transferred from: http://blog.csdn.net/initphp/article/details/7676129
PHP design mode Series-Adapters