当前位置:Gxlcms > PHP教程 > php观察者模式入门例子

php观察者模式入门例子

时间:2021-07-01 10:21:17 帮助过:19人阅读

  1. class DemoSubject implements SplSubject{
  2. private $observers, $value;
  3. public function __construct(){
  4. $this->observers = array();
  5. }
  6. public function attach(SplObserver $observer){
  7. $this->observers[] = $observer;
  8. }
  9. public function detach(SplObserver $observer){
  10. if($idx = array_search($observer, $this->observers, true)){
  11. unset($this->observers[$idx]);
  12. }
  13. }
  14. public function notify(){
  15. foreach($this->observers as $observer){
  16. $observer->update($this);
  17. }
  18. }
  19. public function setValue($value){
  20. $this->value = $value;
  21. $this->notify();
  22. }
  23. public function getValue(){
  24. return $this->value;
  25. }
  26. }
  27. class DemoObserver implements SplObserver{
  28. public function update(SplSubject $subject){
  29. echo 'The new value is '. $subject->getValue();
  30. }
  31. }
  32. $subject = new DemoSubject();
  33. $observer = new DemoObserver();
  34. $subject->attach($observer);
  35. $subject->setValue(5);

人气教程排行