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 ); //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 via 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 away...";
}
}
$huhansan = new Boss(); // Observer
$gongshil = new StockObserver("三毛",$huhansan); //Initialize 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"); //Meet the conditions that are met
$huhansan-> ;Notify(); //Through all valid observers
can be roughly understood as a class (we call it the observer), which inherits an observer container Excuse
The methods in this interface are: add observer, kick out observer, remind observer, and observation condition
Adding observer is equivalent to registering some classes into this container. Of course, these classes The premise is that there needs to be a method that responds to the observed response information.
The observed container determines whether it needs to remind all registered observers in this container by accepting different observation condition parameters.
Once When the reminder conditions are met, all observers in the container are reminded to call the corresponding methods and implement changes to the corresponding observer instances
That’s it for now!
http://www.bkjia.com/PHPjc/321454.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/321454.htmlTechArticleObserver mode copy code code is as follows: interface Subject { public function Attach($Observer); //Add observer public function Detach($Observer); //Kick out the observer public funct...
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn