Observer mode
Copy Code code as follows:
Interface Subject
{
Public Function Attach ($Observer); Add Observer
Public Function Detach ($Observer); Kick out The Observer
Public function Notify (); Notify observers when conditions are met
Public Function subjectstate ($Subject); Observation 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 through method
}
Class Stockobserver extends Observer
{
Public function __construct ($name, $sub)
{
Parent::__construct ($name, $sub);
}
Public Function Update ()
{
echo $this->_sub->_action $this->_username. "You run quickly ...";
}
}
$huhansan = new Boss (); The person being observed
$gongshil = new Stockobserver ("Sanmao", $huhansan); Initialize Observer
$huhansan->attach ($gongshil); Add an Observer
$huhansan->attach ($gongshil); Add an observer of the same
$huhansan->detach ($gongshil); Kick out an observer in the base
$huhansan->subjectstate ("The police came"); Meet the conditions of the meeting
$huhansan->notify (); Through all the effective observers
It can be roughly understood that a class, which we call the Observer, inherits an excuse for the observer's container.
The methods in this interface are: Adding observers, kicking out observers, reminding observers, and observing conditions
Adding an observer is tantamount to registering some classes into the container, which, of course, presupposes a method of responding to the information of the corresponding observer,
The observed container is judged by the acceptance of different observation parameters to see if all the registered observers in this container should be reminded of the corresponding
Once the reminder condition is met, remind all the observers in the container to call the appropriate method and implement the changes to the observer instance
For the moment to understand this!