ariestamirra

observer

Aug 2nd, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.20 KB | None | 0 0
  1. <?php
  2. abstract class AbstractObserver
  3. {
  4.     abstract function update(AbstractSubject $subject_in);
  5. }
  6. abstract class AbstractSubject
  7. {
  8.     abstract function attach(AbstractObserver $observer_in);
  9.     abstract function detach(AbstractObserver $observer_in);
  10.     abstract function notify();
  11. }
  12. function writeln($line_in)
  13. {
  14.     echo $line_in . "<br/>";
  15. }
  16. class PatternObserver extends AbstractObserver
  17. {
  18.     public function __construct()
  19.     {
  20.     }
  21.     public function update(AbstractSubject $subject)
  22.     {
  23.         writeln('*IN PATTERN OBSERVER - NEW PATTERN GOSSIP ALERT*');
  24.         writeln(' new favorite patterns: ' . $subject->getFavorites());
  25.         writeln('*IN PATTERN OBSERVER - PATTERN GOSSIP ALERT OVER*');
  26.     }
  27. }
  28. class PatternSubject extends AbstractSubject
  29. {
  30.     private $favoritePatterns = NULL;
  31.     private $observers = array();
  32.     function __construct()
  33.     {
  34.     }
  35.     function attach(AbstractObserver $observer_in)
  36.     {
  37.         //could also use array_push($this->observers, $observer_in);
  38.         $this->observers[] = $observer_in;
  39.     }
  40.     function detach(AbstractObserver $observer_in)
  41.     {
  42.         //$key = array_search($observer_in, $this->observers);
  43.         foreach ($this->observers as $okey => $oval) {
  44.             if ($oval == $observer_in) {
  45.                 unset($this->observers[$okey]);
  46.             }
  47.         }
  48.     }
  49.     function notify()
  50.     {
  51.         foreach ($this->observers as $obs) {
  52.             $obs->update($this);
  53.         }
  54.     }
  55.     function updateFavorites($newFavorites)
  56.     {
  57.         $this->favorites = $newFavorites;
  58.         $this->notify();
  59.     }
  60.     function getFavorites()
  61.     {
  62.         return $this->favorites;
  63.     }
  64. }
  65. writeln('BEGIN TESTING OBSERVER PATTERN');
  66. writeln('');
  67. $patternGossiper  = new PatternSubject();
  68. $patternGossipFan = new PatternObserver();
  69. $patternGossiper->attach($patternGossipFan);
  70. $patternGossiper->updateFavorites('abstract factory, decorator,
  71. visitor');
  72. $patternGossiper->updateFavorites('abstract factory, observer,
  73. decorator');
  74. $patternGossiper->detach($patternGossipFan);
  75. $patternGossiper->updateFavorites('abstract factory, observer, paisley');
  76. writeln('END TESTING OBSERVER PATTERN');
  77. ?>
Advertisement
Add Comment
Please, Sign In to add comment