User Tools

Site Tools


python:observerpat

OBSERVER PATTERN

11.01.2012

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# OBSERVER PATTERN
#
 
class Observable(object):
    def __init__(self): self._observers = []
 
    def attach(self, observer):
        if observer not in self._observers:
            self._observers.append(observer)
 
    def detach(self, observer):
        if observer in self._observers:
            self._observers.remove(observer)
 
    def notify(self):
        for observer in self._observers:
            observer(self)
 
    def get_notification(self):
        '''just in case if a class forgets about it'''
        return ''
 
 
def log_to_file(obj):
    print "++ Log to file: {}".format(obj.get_notification())
 
def log_to_db(obj):
    print "++ Log to db: {}".format(obj.get_notification())    
 
 
class User(Observable):
    def __init__(self):
        Observable.__init__(self)
 
    def do_some_work(self):
        print 
        print "here some work"
        print "now we notify"
        self.notify()
 
    def get_notification(self):
        return "here the notification string is formatted with respect to each class needs"

Usage:

user1 = User()
 
user1.attach(log_to_file)
user1.attach(log_to_db)
 
user1.do_some_work()
 
user1.detach(log_to_db)
 
user1.do_some_work()
 
user2 = User()
user2.attach(log_to_db)
user2.do_some_work()

and the result:

here some work
now we notify
++ Log to file: here the notification string is formatted with respect to each class needs
++ Log to db: here the notification string is formatted with respect to each class needs

here some work
now we notify
++ Log to file: here the notification string is formatted with respect to each class needs

here some work
now we notify
++ Log to db: here the notification string is formatted with respect to each class needs

python/observerpat.txt · Last modified: 2013/03/16 17:41 (external edit)