Design: Observer Pattern Implementation
Design and implement the core observer pattern components including subject and observers. Out of scope are UI frameworks or network communication.
Functional Requirements
Non-Functional Requirements
Jump into concepts and practice - no test required
+----------------+
| Subject |
|----------------|
| - observers[] |
| + attach() |
| + detach() |
| + notify() |
+--------+-------+
|
+----------+----------+
| |
+---------------+ +---------------+
| Observer 1 | | Observer 2 |
|---------------| |---------------|
| + update() | | + update() |
+---------------+ +---------------+What is the main purpose of the Observer pattern in system design?
Which of the following is the correct way to register an observer in the Observer pattern?
subject = Subject()
observer = ConcreteObserver()
# What code registers the observer?attach or addObserver to register observers.addObserver is used in some languages, attach is the classic and widely accepted method name.Given this code snippet, what will be printed?
class Subject:
def __init__(self):
self.observers = []
self.state = 0
def attach(self, observer):
self.observers.append(observer)
def set_state(self, state):
self.state = state
for obs in self.observers:
obs.update(state)
class Observer:
def __init__(self, name):
self.name = name
def update(self, state):
print(f"{self.name} received state {state}")
subject = Subject()
obs1 = Observer('A')
obs2 = Observer('B')
subject.attach(obs1)
subject.attach(obs2)
subject.set_state(5)set_state(5) is called, it updates the state and calls update(5) on each observer.Identify the bug in this Observer pattern implementation:
class Subject:
def __init__(self):
self.observers = set()
def attach(self, observer):
self.observers.add(observer)
def notify(self):
for obs in self.observers:
obs.update()
class Observer:
def update(self, state):
print(f"State updated to {state}")
subject = Subject()
obs = Observer()
subject.attach(obs)
subject.notify()update method expects a state argument, but notify calls update() without any argument.You are designing a stock price alert system using the Observer pattern. Multiple clients want updates only when the stock price changes by more than 5%. How should you modify the Observer pattern to handle this efficiently?