Middle
What is the Observer pattern?
sobes.tech AI
Answer from AI
Observer Pattern — is a behavioral design pattern that defines a "one-to-many" interaction between objects. In it, the subject (publisher) notifies its observers (subscribers) about changes in its state.
Essence:
- Subject (Publisher): Contains the state of interest to observers. Has methods to add/remove observers and notify them.
- Observer (Subscriber): Defines an interface for receiving notifications from the subject. Each observer implements this interface.
How it works:
- Observers "subscribe" to events or state changes of the subject.
- When the state of the subject changes, it goes through its list of observers and calls their notification method.
- Observers react to the notification, usually by getting the updated state from the subject.
Advantages:
- Loose coupling: The subject does not know the specific observers, interacting only through a common interface.
- Flexibility: Easily add, remove, or modify observers without changing the subject's code.
- Supports the "Open/Closed Principle": Can extend functionality by adding new observers without modifying existing code.
Disadvantages:
- Potential issues with notification order: If the order in which observers receive notifications is important, additional logic may be required.
- Memory leaks: If an observer does not unsubscribe from the subject, it may remain in memory even if no longer needed.
Applications:
- GUI applications: Updating multiple interface elements when data changes.
- Event systems: Propagating events between components.
- Chat applications: Notifying users about new messages.
- RSS readers: Notification about new articles.
Example (pseudocode):
# Observer Interface
interface Observer:
method update(subject_state):
pass
# Subject
class Subject:
state
observers = []
method attach(observer):
add observer to observers list
method detach(observer):
remove observer from observers list
method notify():
for observer in observers:
observer.update(self.state)
method change_state(new_state):
self.state = new_state
self.notify()
# Concrete Observer
class ConcreteObserver(Observer):
method update(subject_state):
print("State changed:", subject_state)
# Usage
subject = Subject()
observer1 = ConcreteObserver()
observer2 = ConcreteObserver()
subject.attach(observer1)
subject.attach(observer2)
subject.change_state("New State 1")
subject.change_state("New State 2")
subject.detach(observer1)
subject.change_state("New State 3")