模式绕晕了 问一下Login::handleLogin()怎么调用
程序员文章站
2022-06-05 13:21:05
...
interface Observable{ function attach(Observer $observer); function detach(Observer $observer); function notify();}// ...login类class Login implements Observable{ private $observers; private $status = array(); const LOGIN_USER_UNKNOWN = 1; const LOGIN_WRONG_PASS = 2; const LOGIN_ACCESS = 3; function __construct(){ $this->observers = array(); } function attach(Observer $observer){ $this->observers[] = $observer; } function detach(Observer $observer){ $newobservers[] = array(); foreach ($this->observers as $obs){ if ( ($obs !== $observer)){ $newservers[] = $obs; } } $this->observers = $newobservers; } function notify(){ foreach ($this->observers as $obs){ $obs->update($this); } } private function setStatus($status, $user, $ip){ $this->status = array($status, $user, $ip); } function getStatus(){ return $this->status; } function handleLogin($user, $pass, $ip){ switch (rand(1,3)){ case 1: $this->setStatus(self::LOGIN_ACCESS, $user, $ip); $ret = true; break; case 2: $this->setStatus(self::LOGIN_WRONG_PASS, $user, $ip); $ret = false; break; case 3: $this->setStatus(self::LOGIN_USER_UNKNOWN, $user, $ip); $ret = false; break; } $this->notify(); return $ret; }}interface Observer{ function update(Observable $observable);}/* class SecurityMonitor implements Observer{ function update(Observable $observable){ // print_r($Observable);exit; $status = $observable->getStatus(); if ($status[0] == Login::LOGIN_WRONG_PASS){ // 发送邮件给系统管理员 print __CLASS__ . ": $status[1] sending mail to sysadmin
"; } }}$login = new Login();$login->attach(new SecurityMonitor());$login->handleLogin('root', 'root', '127.0.0.1');*/abstract class LoginObserver implements Observer{ private $login; function __construct(Login $login){ $this->login = $login; $login->attach($this); } function update(Observable $observable){ if ($observable === $this->login){ $this->doUpdate($observable); } } abstract function doUpdate(Login $login);}class SecurityMonitor extends LoginObserver{ function doUpdate(Login $login){ $status = $login->getStatus(); if ($status[0] == Login::LOGIN_WRONG_PASS){ // 发送邮件给系统管理员 print __CLASS__ . ": sending mail to sysadmin
"; } }}class GeneralLogger extends LoginObserver{ function doUpdate(Login $login){ $status = $login->getStatus(); // 记录登陆数据到日志 print __CLASS__ . ": add login data to log
"; }}class PartnershipTool extends LoginObserver{ function doUpdate(Login $login){ $status = $login->getStatus(); // 检查IP地址 // 如果匹配列表,则设置cookie print __CLASS__ . ": set cookie if IP matches a list
"; }}$login = new Login();new SecurityMonitor($login);new GeneralLogger($login);new PartnershipTool($login);
类图
模式绕晕了 问一下Login::handleLogin()怎么调用
回复讨论(解决方案)
你 80 到 82 行注释掉的代码不就是调用方式吗?
不过 handleLogin 内部居然以随机方式工作。不明白你要干什么
你 80 到 82 行注释掉的代码不就是调用方式吗?
不过 handleLogin 内部居然以随机方式工作。不明白你要干什么
谢谢