Advertisement
Guest User

observer

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