User Tools

Site Tools


python:observerpat

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

python:observerpat [2013/03/16 17:41] (current)
Line 1: Line 1:
 +==== OBSERVER PATTERN ====
 +11.01.2012
  
 +
 +<code python>
 +#​!/​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"
 +</​code>​
 +
 +
 +Usage:
 +
 +<code python>
 +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()
 +</​code>​
 +
 +and the result:
 +
 +<​code>​
 +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
 +</​code>​
python/observerpat.txt ยท Last modified: 2013/03/16 17:41 (external edit)