<?php
interface Observable{
function attach(Observer $observer);
function detach(Observer $observer);
function notify();
}
class Login implements Observable{
private $observers;
const LOGIN_ACCESS=1;
const LOGIN_WRONG_PASS=2;
const LOGIN_USER_UNKNOWN=3;
private $status=array();
function handlerLogin($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;
}
private function setStatus($status,$user,$ip){
$this->status=array($status,$user,$ip);
}
function getStatus(){
return $this->status;
}
function attach(Observer $observer){
$this->observers[]=$observer;
}
function detach(Observer $observer){
$newobservers=array();
foreach($this->observers as $obs){
if(($obs !==$observer)){
$newobservers[]=$obs;
}
}
$this->observers=$newobservers;
}
function notify(){
foreach($this->observers as $obs){
$obs->update($this);
}
}
}
interface Observer{
function update(Observable $observable);
}
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_USER_UNKNOWN){
print __CLASS__.": \tsending mail to sysadmin\n <br>";
}
}
}
class GeneralLogger extends LoginObserver{
function doUpdate(Login $login){
$status=$login->getStatus();
if($status[0]==Login::LOGIN_WRONG_PASS){
print __CLASS__.": \t 记录登陆日志数据 <br>";
}
}
}
class PartnershipTool extends LoginObserver{
function doUpdate(Login $login){
$status=$login->getStatus();
if($status[0]==Login::LOGIN_USER_UNKNOWN){
print __CLASS__." \t 检查IP地址,匹配列表设置cookie <br>";
}
}
}
$login=new Login();
new SecurityMonitor($login);
new GeneralLogger($login);
new PartnershipTool($login);
$login->handlerLogin("xiaowei","fdfd","123");
?>
|