Observer pattern
Copy code The code is as follows:
interface Subject
{
public function Attach($Observer); //Add an observer
public function Detach($Observer); //Kick out the observer
public function Notify(); //Notify the observer when the conditions are met
public function SubjectState($Subject); //Observe the conditions
}
class Boss Implements Subject
{
public $_action;
private $_Observer;
public function Attach($Observer)
{
$this->_Observer[] = $Observer;
}
public function Detach($Observer)
{
$ObserverKey = array_search($Observer, $this->_Observer);
if($ObserverKey !== false)
{
unset($this->_Observer[$ObserverKey]);
}
}
public function Notify()
{
foreach($this->_Observer as $value )
{
$value->Update();
}
}
public function SubjectState($Subject)
{
$this->_action = $Subject;
}
}
abstract class Observer
{
protected $_UserName;
protected $_Sub;
public function __construct($Name,$Sub)
{
$this->_UserName = $Name;
$this->_Sub = $Sub;
}
public abstract function Update (); //Receive via method
}
class StockObserver extends Observer
{
public function __construct($name,$sub)
{
parent::__construct($name,$sub);
}
public function Update( )
{
echo $this->_Sub->_action.$this->_UserName." Run quickly...";
}
}
$huhansan = new Boss(); // Observer
$gongshil = new StockObserver("三毛",$huhansan); //Initialize the observer
$huhansan->Attach($gongshil); //Add an observer
$huhansan->Attach($gongshil) ; //Add an identical observer
$huhansan->Detach($gongshil); //Kick out an observer in the base
$huhansan->SubjectState("The police are coming"); //Achieve satisfactory results Condition
$huhansan->Notify(); //All valid observers
The above introduces the observer mode in php, including observer aspects. I hope it will be helpful to friends who are interested in PHP tutorials.