17 May 2015
Observer Pattern
Sometimes you need to watch for a variable for changes and take actions according to value. Observer pattern is often used for those cases. It also helps us to separate responsibilities between modules.
Wikipedia: The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
Example:
Just think we are developing a game. There is an observer in the game, and this observer communicates with the units if it saw an enemy. It calls a method of Unit classes which previously registered to itself. Let's see it on example.
class Unit:
def __init__(self, name):
self.name = name
def update(self, *args, **kwargs):
print "%s closing to enemies!" % self.name
class Observer:
units = set()
def register(self, unit):
self.units.add(unit)
def unregister(self, unit):
self.units.discard(unit)
def saw_somehing(self, *args, **kwargs):
for unit in self.units:
unit.update(*args, **kwargs)
blue_team = Unit(name="Blue Team")
red_team = Unit(name="Red Team")
observer = Observer()
observer.register(blue_team)
observer.register(red_team)
observer.saw_somehing()
>>> "Blue Team closing to enemies!"
>>> "Red Team closing to enemies!"
observer.unregister(blue_team)
observer.saw_somehing()
>>> "Red Team closing to enemies!"
References: