Sobes.tech
Junior — Middle

Can you explain the observer pattern concept and its application?

sobes.tech AI

Answer from AI

The "Observer" pattern is used to organize communication between objects, where one object (the publisher) notifies other objects (observers) about changes in its state.

Applications:

  • Allows for loose coupling between components.
  • Often used in GUIs to update the interface when data changes.
  • In event-driven systems and subscriptions.

Example in Python:

class Subject:
    def __init__(self):
        self._observers = []
        self._state = None

    def attach(self, observer):
        self._observers.append(observer)

    def detach(self, observer):
        self._observers.remove(observer)

    def notify(self):
        for observer in self._observers:
            observer.update(self._state)

    def set_state(self, state):
        self._state = state
        self.notify()

class Observer:
    def update(self, state):
        print(f"Observer received new state: {state}")

subject = Subject()
observer1 = Observer()
observer2 = Observer()

subject.attach(observer1)
subject.attach(observer2)

subject.set_state('New state')

In this example, when the state of the Subject object changes, all subscribed observers receive a notification and react to it.

Can you explain the observer pattern concept and its… - sobes.tech