Monday, July 09, 2007

Mediator Pattern in Python


1 class Mediator(object):
2 def __init__(self):
3 self.signals = {}
4
5 def signal(self, signal_name, *args, **kw):
6 for handler in self.signals.get(signal_name, []):
7 handler(*args, **kw)
8
0 def connect(self, signal_name, receiver):
10 handlers = self.signals.setdefault(signal_name, [])
11 handlers.append(receiver)
12
13 def disconnect(self, signal_name, receiver):
14 handlers[signal_name].remove(receiver)

This class helps promote loose coupling in my games. I imagine that with a few lines from Pygnet, I could probably 'loosely couple' objects over a network. :-)

2 comments:

Carl the Great said...

I am having trouble visualizing how you use this. Would you sometime post a short bit of code or an explanation of how you are using it? Thank you.

Simon Wittber said...

There is an example on the pygame wiki where a mediator class (EventManager) is used to connect Model, View and controller classes together. This is my primary use-case too.

Popular Posts