public function testObserver() { $subject = new ConcreteSubject(); $subject->attach(new ConcreteObserver()); $subject->attach(new ConcreteObserver()); $subject->attach($c = new ConcreteObserver()); $subject->state = "New State..."; $subject->Notify(); $this->assertEquals($subject->state, $c->state); }
public function __construct() { echo "Tworzenie 3 konkretnych obserwatorów i konkretnego podmiotu <BR>"; $ob1 = new ConcreteObserver(); $ob2 = new ConcreteObserver(); $ob3 = new ConcreteObserver(); $subject = new ConcreteSubject(); $subject->setObservers(); $subject->setData("Oto twoje dane!"); $subject->attach($ob1); $subject->attach($ob2); $subject->attach($ob3); $subject->notify(); echo "Odpięcie obserwatora ob3. Powiadamiane będą ob1 i ob2<BR>"; $subject->detach($ob3); $subject->notify(); echo "Reset danych, podpięcie ob3 i dopięcie ob2, tylko ob1 i ob3 będą powiadamiane: <BR>"; $subject->setData("Dane dla obiektów ob1 i ob3"); $subject->attach($ob3); $subject->detach($ob2); $subject->notify(); }
public function update(SplSubject $subject) { echo 'ConcreteObserver2 state is ', $subject->getState(), '<br>'; } } /** * 具体观察者 3 * */ class ConcreteObserver3 extends bserver implements SplObserver { function __construct($state) { parent::__construct($state); } public function update(SplSubject $subject) { echo 'ConcreteObserver3 state is ', $subject->getState(), '<br>'; } } $subject = new ConcreteSubject(); $observer1 = new ConcreteObserver1(1); $observer2 = new ConcreteObserver2(2); $observer3 = new ConcreteObserver3(3); $subject->attach($observer1); $subject->attach($observer2); $subject->attach($observer3); echo 'Subject state is 1', '<br>'; $subject->setState(1); echo 'Subject state is 2', '<br>'; $subject->setState(3);
* 具体通知者类 */ class ConcreteSubject extends Subject { public $state; } /* * 具体观察者 */ class ConcreteObserver extends Observer { private $_name; private $_subject; public function __construct($name, Subject $subject) { $this->_name = $name; $this->_subject = $subject; } public function update() { var_dump(sprintf('观察者:%s,通知者的状态是:%s,请做出相应的反应。', $this->_name, $this->_subject->state)); } } ################################################################################### $concreteSubject = new ConcreteSubject(); //通知者 $concreteObserver = new ConcreteObserver('张三', $concreteSubject); //观察者 $concreteSubject->attach($concreteObserver); $concreteSubject->state = 'abc'; $concreteSubject->notify();
/** * Main program. */ public static function main() { $subject = new ConcreteSubject(); /* 添加第一个观察者 */ $observer1 = new ConcreteObserver("Martin"); $subject->attach($observer1); echo "\nThe First notify:\n"; $subject->notifyObservers(); /* 添加第二个观察者 */ $observer2 = new ConcreteObserver("phppan"); $subject->attach($observer2); echo "\nThe Second notify:\n"; $subject->notifyObservers(); /* 删除第一个观察者 */ $subject->detach($observer1); echo "\nThe Third notify:\n"; $subject->notifyObservers(); }