An example of an observer pattern of Python design patterns

  • 2020-04-02 13:40:07
  • OfStack

The observer pattern in design patterns is defined as follows (wikipedia) :

The actor mode is a part of the actor mode. In this hang mode, a hang object manages all the attendant objects that are attached to it, and the hang modifies the main hang in its own. The impersonator usually calls the method provided by the impersonator. This mode is usually used as an event - mode.
In short, an observed has many observers, and a change in the state of the observed causes all observers to respond.

So we use Python2.7 to implement the observer mode.


Set in Python

A set is similar to a list, but it has no duplicate elements. Its doc is as follows:


>>> print set.__doc__
set() -> new empty set object
set(iterable) -> new set object
Build an unordered collection of unique elements.

The following are a few simple collection operations in ipython.

In [1]: myset = set()
In [2]: myset.add(1)
In [3]: myset.add(2)
In [4]: myset.add('s')
In [5]: print myset
set([1, 2, 's'])
In [6]: myset.add('s')
In [7]: print myset
set([1, 2, 's'])
In [8]: myset.remove(3)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-8-a93073f8a2af> in <module>()
----> 1 myset.remove(3)
KeyError: 3
In [9]: myset.remove(1)
In [10]: print myset
set([2, 's'])

The built-in set() can generate an empty collection object, or it can pass some parameters in the set, such as a list:

>>> print set([1,2,3,3])
set([1, 2, 3])

The most commonly used method is to add and remove the more content you can refer to http://docs.python.org/2/library/stdtypes.html#set.

A simple implementation of the observer pattern


class Observer(object):
    def __init__(self, s):
        self.s = s
    def update(self):
        print self.s
if __name__ == '__main__':
    foo01 = Observer("hi, i am foo01")
    foo02 = Observer("hi, i am foo02")
    observers = set()
    observers.add(foo01)
    observers.add(foo01)
    observers.add(foo02)
    print observers
    for ob in observers:
        ob.update()

Here are the results:

set([<__main__.Observer object at 0xb74627cc>, <__main__.Observer object at 0xb74627ec>])
hi, i am foo01
hi, i am foo02

The first line in the result is the contents of the set observers, which contain two Observer instances whose memory addresses may differ from run to run. while

for ob in observers:
    ob.update()

You can view it as multiple observers and generate a response.

Of course, this implementation is not good -- the observed should be an instance, too.

A more complete implementation of the observer pattern


class ObserverInterface(object):
    def __init__(self):
        pass
    def update(self):
        pass
class SubjectInterface(object):
    def __init__(self):
        self.observers = set()
    def addObserver(self, ob):
        self.observers.add(ob)
    def delObserver(self, ob):
        self.observers.remove(ob)
    def notifyObservers(self):
        for ob in self.observers:
            ob.update()
class Observer01(ObserverInterface):
    def __init__(self, s):
        self.s = s
    def update(self):
        print self.s
class Observer02(ObserverInterface):
    def __init__(self, num1, num2):
        self.num1 = num1
        self.num2 = num2
    def update(self):
        print self.num1 + self.num2
class Subject01(SubjectInterface):
    def __init__(self):
        SubjectInterface.__init__(self)
if __name__ == '__main__':
    ob01 = Observer01("hi, i am ob01")
    ob02 = Observer02("hello,","i am ob02")
    observers = set()
    sb01 = Subject01()
    sb01.addObserver(ob01)
    sb01.addObserver(ob02)
    sb01.notifyObservers()

The operation results are as follows:

hi, i am ob01
hello,i am ob02


Related articles: