Example of the observer pattern for Python design patterns

Source: Internet
Author: User
For the Observer pattern in design mode, the definition is as follows (Wikipedia):

The Observer pattern (sometimes referred to as the release/subscribe mode) is one of the software design modes. In this mode, a target object manages all the observer objects that are dependent on it and, in its own state, changes the notification of the host. This is usually done by calling the methods provided by the viewers. This pattern is often used as an event management system.
Simply put, an observer has many observers, and changes in the state of the observer will cause all observers to respond.

Then we use Python2.7 to implement the observer pattern.


Collection set in Python

Collection (set), similar to a list, but it has no duplicate elements, and its doc content is as follows:

The code is as follows:


>>> Print set.__doc__
Set (), new empty Set object
Set (iterable), new set Object

Build an unordered collection of unique elements.


Here are a few simple collection operations that are performed in Ipython.

The code is as follows:


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)
In ()
----> 1 myset.remove (3)

Keyerror:3

In [9]: Myset.remove (1)

In [ten]: Print MySet
Set ([2, ' s '])


A built-in set () can produce an empty collection object, or you can pass in a set with some parameters, such as a list:

The code is as follows:


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


The most common method is add and remove, and more content can refer to Http://docs.python.org/2/library/stdtypes.html#set.

Implementation of a simple observer pattern

The code is as follows:


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 is the result of the operation:

The code is as follows:


Set ([<__main__. Observer object at 0xb74627cc> <__main__. Observer object at 0xb74627ec>])
Hi, I am foo01
Hi, I am foo02


The first row in the run result is the contents of the collection observers, which contains two observer instances where the memory address may be different at each run. and

The code is as follows:


For OB in observers:
Ob.update ()


Can be seen as a response from multiple observers.

Of course, this implementation is not good-the observer should also be an example.

A more sophisticated observer pattern implementation

The code is as follows:


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 results of the operation are as follows:

The code is as follows:


Hi, I am ob01
Hello,i am OB02

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.