Sample source of Observer pattern realized by Java, PHP, Python

*** Observer pattern *** is a type of design pattern used in the process of notifying other objects of an event (event) of an object in the program. This is called because the object side to be notified is observed by the object side to be notified (English: observe). Also known as the publish-subscribe model. It is closely related to the principle of implicit calling. It is also used to implement a distributed event processing system. Depending on the language, the problems dealt with in this pattern are handled by the language's event handling syntax.

Observer-pattern-class-diagram.png

Observer pattern in Java

import java.util.ArrayList;

interface Observer {
       public void update(float interest);
}

interface Subject {
       public void registerObserver(Observer observer);
       public void removeObserver(Observer observer);
       public void notifyObservers();
}

class Loan implements Subject {
       private ArrayList<Observer> observers = new ArrayList<Observer>();
       private String type;
       private float interest;
       private String bank;

       public Loan(String type, float interest, String bank) {
              this.type = type;
              this.interest = interest;
              this.bank = bank;
       }

       public float getInterest() {
              return interest;
       }

       public void setInterest(float interest) {
              this.interest = interest;
              notifyObservers();
       }

       public String getBank() {
              return this.bank;
       }

       public String getType() {
              return this.type;
       }

       @Override
       public void registerObserver(Observer observer) {
              observers.add(observer);

       }

       @Override
       public void removeObserver(Observer observer) {
              observers.remove(observer);

       }

       @Override
       public void notifyObservers() {
            for (Observer ob : observers) {
                System.out.println("Notifying Observers on change in Loan interest rate");
                ob.update(this.interest);
            }

       }

}

class Newspaper implements Observer {
       @Override
       public void update(float interest) {
              System.out.println("Newspaper: Interest Rate updated, new Rate is: " + interest);
       }
}

class Internet implements Observer {
       @Override
       public void update(float interest) {
              System.out.println("Internet: Interest Rate updated, new Rate is: "
                           + interest);
       }
}

public class ObserverTest {

       public static void main(String args[]) {
              // this will maintain all loans information
              Newspaper printMedia = new Newspaper();
              Internet onlineMedia = new Internet();

              Loan personalLoan = new Loan("Personal Loan", 12.5f,
                           "Standard Charterd");
              personalLoan.registerObserver(printMedia);
              personalLoan.registerObserver(onlineMedia);
              personalLoan.setInterest(3.5f);

       }
}

Observer pattern in PHP

<?php

abstract class AbstractObserver {
    abstract function update(AbstractSubject $subject_in);
}

abstract class AbstractSubject {
    abstract function attach(AbstractObserver $observer_in);
    abstract function detach(AbstractObserver $observer_in);
    abstract function notify();
}

function writeln($line_in) {
    echo $line_in."<br/>";
}

class PatternObserver extends AbstractObserver {
    public function __construct() {
    }
    public function update(AbstractSubject $subject) {
      writeln('*IN PATTERN OBSERVER - NEW PATTERN GOSSIP ALERT*');
      writeln(' new favorite patterns: '.$subject->getFavorites());
      writeln('*IN PATTERN OBSERVER - PATTERN GOSSIP ALERT OVER*');      
    }
}

class PatternSubject extends AbstractSubject {
    private $favoritePatterns = NULL;
    private $observers = array();
    function __construct() {
    }
    function attach(AbstractObserver $observer_in) {
      //could also use array_push($this->observers, $observer_in);
      $this->observers[] = $observer_in;
    }
    function detach(AbstractObserver $observer_in) {
      //$key = array_search($observer_in, $this->observers);
      foreach($this->observers as $okey => $oval) {
        if ($oval == $observer_in) { 
          unset($this->observers[$okey]);
        }
      }
    }
    function notify() {
      foreach($this->observers as $obs) {
        $obs->update($this);
      }
    }
    function updateFavorites($newFavorites) {
      $this->favorites = $newFavorites;
      $this->notify();
    }
    function getFavorites() {
      return $this->favorites;
    }
}

  writeln('BEGIN TESTING OBSERVER PATTERN');
  writeln('');

  $patternGossiper = new PatternSubject();
  $patternGossipFan = new PatternObserver();
  $patternGossiper->attach($patternGossipFan);
  $patternGossiper->updateFavorites('abstract factory, decorator, visitor');
  $patternGossiper->updateFavorites('abstract factory, observer, decorator');
  $patternGossiper->detach($patternGossipFan);
  $patternGossiper->updateFavorites('abstract factory, observer, paisley');

  writeln('END TESTING OBSERVER PATTERN');

?>

Output result

BEGIN TESTING OBSERVER PATTERN

*IN PATTERN OBSERVER - NEW PATTERN GOSSIP ALERT*
new favorite patterns: abstract factory, decorator, visitor
*IN PATTERN OBSERVER - PATTERN GOSSIP ALERT OVER*

*IN PATTERN OBSERVER - NEW PATTERN GOSSIP ALERT*
new favorite patterns: abstract factory, observer, decorator
*IN PATTERN OBSERVER - PATTERN GOSSIP ALERT OVER*

END TESTING OBSERVER PATTERN

Observer pattern in Python

"""
Define a one-to-many dependency between objects so that when one object
changes state, all its dependents are notified and updatedautomatically.
"""

import abc


class Subject:
    """
    Know its observers. Any number of Observer objects may observe a
    subject.
    Send a notification to its observers when its state changes.
    """

    def __init__(self):
        self._observers = set()
        self._subject_state = None

    def attach(self, observer):
        observer._subject = self
        self._observers.add(observer)

    def detach(self, observer):
        observer._subject = None
        self._observers.discard(observer)

    def _notify(self):
        for observer in self._observers:
            observer.update(self._subject_state)

    @property
    def subject_state(self):
        return self._subject_state

    @subject_state.setter
    def subject_state(self, arg):
        self._subject_state = arg
        self._notify()


class Observer(metaclass=abc.ABCMeta):
    """
    Define an updating interface for objects that should be notified of
    changes in a subject.
    """

    def __init__(self):
        self._subject = None
        self._observer_state = None

    @abc.abstractmethod
    def update(self, arg):
        pass


class ConcreteObserver(Observer):
    """
    Implement the Observer updating interface to keep its state
    consistent with the subject's.
    Store state that should stay consistent with the subject's.
    """

    def update(self, arg):
        self._observer_state = arg
        # ...


def main():
    subject = Subject()
    concrete_observer = ConcreteObserver()
    subject.attach(concrete_observer)
    subject.subject_state = 123


if __name__ == "__main__":
    main()

Recommended Posts

Sample source of Observer pattern realized by Java, PHP, Python
Observer pattern in Java
[For beginners] Basics of Python explained by Java Gold Part 2
Java VS PHP VS Python VS Ruby
I just changed the sample source of Python a little.
Sample usage of Python pickle
Source installation and installation of Python
[For beginners] Basics of Python explained by Java Gold Part 1
Observer pattern understood by cats Part 1
Expansion by argument of python dictionary
Chain of Responsibility pattern in Java
Behavior of python3 by Sakura's server
Observer pattern understood by Nyanko Part 2
Story of power approximation by Python
Explanation of production optimization model by Python
[Learning memo] Basics of class by python
Learn the design pattern "Observer" in Python
(Java, JavaScript, Python) Comparison of string processing
PHP / Python / Ruby sample hitting Path API
Conditional branching of Python learned by chemoinformatics
Grayscale by matrix-Reinventor of Python image processing-
Example of 3D skeleton analysis by Python
Pandas of the beginner, by the beginner, for the beginner [Python]
Analysis of X-ray microtomography image by Python
[Gang of Four] Design pattern learning --Observer
Get the last element of the array by splitting the string in Python and PHP