Design Pattern Examples
Overview of object-oriented design patterns
observer_exercise.py
Go to the documentation of this file.
6
7from .observer_class import ObserverForDecimal, ObserverForHexaDecimal, ObserverForBinary
8from .observersubject_numberproducer import ObserverSubject_NumberProducer
9
10
28
29# ! [Using Observer in Python]
31 print()
32 print("Observer Exercise")
33
34 numberProducer = ObserverSubject_NumberProducer()
35
36 # The number producer is passed to the observers so the observers
37 # can get the number to display. The observers only see the
38 # INumberProducer interface, to minimize knowledge about the
39 # Subject.
40 observerDecimal = ObserverForDecimal(numberProducer)
41 observerHexadecimal = ObserverForHexaDecimal(numberProducer)
42 observerBinary = ObserverForBinary(numberProducer)
43
44 # Tell the number producer about the observers who are notified
45 # whenever the value changes.
46 numberProducer.SubscribeToNumberChanged(observerDecimal)
47 numberProducer.SubscribeToNumberChanged(observerHexadecimal)
48 numberProducer.SubscribeToNumberChanged(observerBinary)
49
50 # Call the number producer's Update() method a number of times.
51 # The observers automatically print out the current value in
52 # different bases.
53 for index in range(0, 10):
54 print(" Update {0} on number producer. Results from observers:".format(index))
55 numberProducer.Update();
56
57 # When done, remove the observers from the number producer.
58 # It's always good to clean up after ourselves.
59 numberProducer.UnsubscribeFromNumberChanged(observerDecimal)
60 numberProducer.UnsubscribeFromNumberChanged(observerHexadecimal)
61 numberProducer.UnsubscribeFromNumberChanged(observerBinary)
62
63 print(" Done.")
64# ! [Using Observer in Python]
Represents an observer that prints out the current number from the Subject in binary.
Represents an observer that prints out the current number from the Subject in decimal.
Represents an observer that prints out the current number from the Subject in hexadecimal.
Represents the Subject to be observed; in this case, a class that contains a single number that is up...
def Observer_Exercise()
Example of using the Observer Pattern.