Observer Pattern, Java and Python Example

From Wikipedia: The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems. This post shows an example implemented on Java and Python.

Notification System Example

Let's say that we have a social network, every time that an user makes a change password request, an email and a SMS messages should be send to the user.

Java Implementation

The Subject:

    package co.ntweb.maigfrga.observer;

    import java.util.Observable;

    /* Subject implementation Observer pattern*/

    public class NotificationSubject extends Observable
    {
        public void sendMessage(String message){
            System.out.println( "Change status and notify observers" );
            setChanged();
            notifyObservers(message);
        }

    }

Email observer:

    package co.ntweb.maigfrga.observer;

    import java.util.Observable;
    import java.util.Observer;

    public class EmailObserver implements Observer {
        private String message;

        public void update(Observable obj, Object arg) {
            if (arg instanceof String) {
                message = (String) arg;
                System.out.println("\nSend message by  Email: " + message );
            }
        }
    }

SMS Observer

    package co.ntweb.maigfrga.observer;

    import java.util.Observable;
    import java.util.Observer;

    public class SMSObserver implements Observer {
        private String message;

        public void update(Observable obj, Object arg) {
            if (arg instanceof String) {
                message = (String) arg;
                System.out.println("\nSend message by  SMS: " + message );
            }
        }
    }

Registering the observers

    NotificationSubject subject = new NotificationSubject();
    EmailObserver email_observer = new EmailObserver();
    SMSObserver sms_observer = new SMSObserver();

    subject.addObserver(email_observer);
    subject.addObserver(sms_observer);
    subject.sendMessage("Hello world :-)");

Python Implementation

The Subject:

    class Subject(object):
    """Observer pattern http://en.wikipedia.org/wiki/Observer_pattern
    """
    def __init__(self, *args, **kwargs):
        pass

    def register(self, observer):
        pass

    def unregister(self, observer):
        pass

    def notify_all(self, *args, **kwargs):
        pass

class  NotificationSubject(Subject):
    def __init__(self, *args, **kwargs):
        self._observers = []

    def register(self, observer):
        self._observers.add(observer)

    def unregister(self, observer):
        self._observers.remove(observer)

    def notify_all(self, message):
        for observer in self._observers:
            observer.notify(message)

    def send_message(self, message):
        print 'notification subject'
        self.notify_all(message)

The Observers

    class Observer(object):
        def __init__(self, *args, **kwargs):
            pass

        def notify(self, *args, **kwargs):
            pass


    class EmailObserver(Observer):
        def notify(self, message):
            print '\n Send Email message'

    class SMSObserver(Observer):
        def notify(self, message):
            print '\n Send SMS message'

Registering the observers

    subject = NotificationSubject()
    email_observer = EmailObserver()
    subject.register(email_observer)
    sms_observer = SMSObserver()
    subject.register(sms_observer)
    subject.send_message('Hello world :-)')

Source code can be found at this link