标签:
适配器设计模式只是将某个对象的接口适配为另一个对象所期望的接口。
<?php //早期的一个用户类,只实现获取用户名的方法 class UserInfo { public function getUserName() { return ‘initphp‘; } }
代码:MyOldObject类,从UserInfo类中获取信息,输出用户名
<?php include_once("UserInfo.php"); class MyOldObject { public function write() { $UserInfo = new UserInfo; echo $UserInfo->getUserName(); } } $a = new MyOldObject; $a->write();
代码:UserInfoAdapter类,随着时间推移,项目需求在变化,UserInfo类无法满足需求,我们做了UserInfo类的适配器,满足新功能的需求
<?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() ); } }
代码:MyNewObject类,新功能的类,需要打印出用户年龄和姓名,UserInfo类无法满足需求,需要调用UserInfoAdapter适配器这个类
<?php include_once("UserInfoAdapter.php"); class MyNewObject { public function write() { $UserInfoAdapter = new UserInfoAdapter; print_r($UserInfoAdapter->getUser()); } } $a = new MyNewObject; $a->write();
转自:http://blog.csdn.net/initphp/article/details/7676129
标签:
原文地址:http://www.cnblogs.com/zhhtao/p/4414584.html