Package pypat :: Package behavioral :: Module mediator
[hide private]
[frames] | no frames]

Source Code for Module pypat.behavioral.mediator

 1  from collections import defaultdict 
 2   
 3   
4 -class Mediator(object):
5 """ 6 Mediator class as part of the Mediator design pattern. 7 8 - External Usage documentation: U{https://github.com/tylerlaberge/PyPatterns/wiki/Behavioral-Pattern-Usage} 9 - External Mediator Pattern documentation: U{https://en.wikipedia.org/wiki/Mediator_pattern} 10 """
11 - def __init__(self):
12 """ 13 Initialize a new Mediator instance. 14 """ 15 self.signals = defaultdict(list)
16
17 - def signal(self, signal_name, *args, **kwargs):
18 """ 19 Send a signal out to all connected handlers. 20 21 @param signal_name: The name of the signal. 22 @type signal_name: Str 23 @param args: Positional arguments to send with the signal. 24 @param kwargs: Keyword arguments to send with the signal. 25 """ 26 for handler in self.signals[signal_name]: 27 handler(*args, **kwargs)
28
29 - def connect(self, signal_name, receiver):
30 """ 31 Connect a receiver to a signal. 32 33 @param signal_name: The name of the signal to connect the receiver to. 34 @type signal_name: str 35 @param receiver: A handler to call when the signal is sent out. 36 """ 37 self.signals[signal_name].append(receiver)
38
39 - def disconnect(self, signal_name, receiver):
40 """ 41 Disconnect a receiver from a signal. 42 43 @param signal_name: The name of the signal to disconnect the receiver from. 44 @type signal_name: str 45 @param receiver: The receiver to disconnect from the signal. 46 """ 47 try: 48 self.signals[signal_name].remove(receiver) 49 except ValueError: 50 pass
51