Observer mode
/**
* Define the Observation interface
*/
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
}
/**
* The specific implementation of the observation class
*/
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 Observer
*
*/
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
}
/**
* Observer
*/
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
Policy mode
/**
* Defines the interface of the support algorithm
*
*/
Abstract class Strategy
{
Abstract public Function algorithminterface ();
}
Class Concreatestrata extends Strategy
{
Public Function Algorithminterface ()
{
echo "Algorithm a";
}
}
Class CONCREATESTRATB extends Strategy
{
Public Function Algorithminterface ()
{
echo "Algorithm B";
}
}
Class CONCREATESTRATC extends Strategy
{
Public Function Algorithminterface ()
{
echo "Algorithm C";
}
}
Class context
{
Private $_strobj;
Public function __construct ($strobj)
{
$this->_strobj = $strobj;
}
Public Function Contextinterface ()
{
$this->_strobj->algorithminterface ();
}
}
$context = new Context (new Concreatestrata);
$context->contextinterface ();
$context = new Context (new CONCREATESTRATC);
$context->contextinterface ();
$context = new Context (new CONCREATESTRATB);
$context->contextinterface ();