欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php观察者模式入门例子

程序员文章站 2022-04-15 18:25:25
...
  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);
复制代码