标签:
什么都不说,先看代码:
interface userOperateImpl { public function operate($username); } class userLoginLog implements userOperateImpl { public function operate($username) { echo ‘用户名为 [‘.$username.‘] 的用户登陆记录日志<br/>‘; } } class UserLoginPush implements userOperateImpl { public function operate($username) { echo ‘用户名为 [‘.$username.‘] 的用户登陆推送消息<br/>‘; } } class UserLogin { private $_obj = array(); public $username; public function __construct($username,$_objArr = array()) { $this->username = $username; $this->_obj = $_objArr; } public function userLogin() { echo "用户名为 [".$this->username."] 的用户登陆!<br/>"; $this->trigger(); } private function trigger() { if(!empty($this->_obj)){ foreach($this->_obj as $obj){ /** @var userOperateImpl $obj */ $obj->operate($this->username); } } } } $user = new UserLogin(‘Mr Li‘, array( new userLoginLog(), new UserLoginPush() ) ); $user->userLogin();
解释:
编写接口userOperateImpl表示用户操作,将登陆记录的日志,推送实现该接口,代表两个观察者.
编写主题类UserLogin,构造函数里出入用户名和观察者,在用户登陆方法中将消息传递给观察者!
注:
标签:
原文地址:http://www.cnblogs.com/sign-ptk/p/5689488.html