The observer(subject) is an object that maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
Example – Python:
class Observable: def __init__(self): self.__observers = [] def register_observer(self, observer): self.__observers.append(observer) def notify_observers(self, *args, **kwargs): for observer in self.__observers: observer.notify(self, *args, **kwargs) class Observer: def __init__(self, observable): observable.register_observer(self) def notify(self, observable, *args, **kwargs): print('Got', args, kwargs, 'From', observable) subject = Observable() observer = Observer(subject) subject.notify_observers('test')
output would be same as below (except instance at will differ in memory address):
('Got', ('test',), {}, 'From', <__main__.Observable instance at 0x7efcf8d4e4d0>)
Comments are closed, but trackbacks and pingbacks are open.