The Observer Pattern is a behavioral design pattern used to establish a one-to-many relationship between objects. In an event-driven application, multiple observers (listeners) subscribe to a subject (event publisher), and whenever an event occurs, the subject automatically notifies all registered observers. This approach promotes loose coupling and makes the system easier to extend and maintain.
Key Points: • Observers can subscribe or unsubscribe dynamically without modifying the event source. • The subject does not need to know the implementation details of its observers, resulting in loose coupling. • The pattern is widely used in GUI frameworks, messaging systems, notification services, and event-driven architectures.
Example: Consider an e-commerce application where an OrderService publishes an "Order Placed" event. Multiple observers such as EmailService, SMSService, and InventoryService can listen to the event and perform their respective actions independently.
Code Example:
import java.util.ArrayList;
import java.util.List;
interface Observer {
void update(String event);
}
class EmailService
implements Observer {
@Override
public void update(String event) {
System.out.println(
"Email Notification: "
+ event);
}
}
class SMSService
implements Observer {
@Override
public void update(String event) {
System.out.println(
"SMS Notification: "
+ event);
}
}
class EventPublisher {
private final List<Observer> observers =
new ArrayList<>();
public void subscribe(
Observer observer) {
observers.add(observer);
}
public void notifyObservers(
String event) {
for (Observer observer : observers) {
observer.update(event);
}
}
}
public class Main {
public static void main(String[] args) {
EventPublisher publisher =
new EventPublisher();
publisher.subscribe(
new EmailService());
publisher.subscribe(
new SMSService());
publisher.notifyObservers(
"Order Placed Successfully");
}
}Interview Tip: A concise interview answer is: In an event-driven application, the Observer Pattern allows listeners to subscribe to an event source. When an event occurs, the source automatically notifies all registered observers, enabling loose coupling, better extensibility, and easier maintenance.