fork download
  1. // ==================================================
  2. // Observer Design Pattern
  3. // ==================================================
  4. //
  5. // What is Observer Pattern?
  6. // Observer Pattern defines a one-to-many dependency between objects
  7. // so that when one object (Subject) changes state, all its dependents
  8. // (Observers) are notified and updated automatically.
  9. //
  10. // It is also known as the Publisher-Subscriber model.
  11. //
  12. // When to use:
  13. // - When a change in one object requires changing others
  14. // - When you want loose coupling between the event source and its listeners
  15. // - When you want to add or remove listeners without modifying the source
  16. //
  17. // Key parts:
  18. // 1. Subject (Publisher) → maintains list of observers and notifies them
  19. // 2. Observer (Subscriber) → interface with an update method
  20. // 3. Concrete Observers → classes that react to the notification
  21. //
  22. // Example used here: Student registration event
  23. // When a student registers, multiple actions should happen:
  24. // - Assign batch
  25. // - Send email
  26. // - Send Slack invite
  27. //
  28. // --------------------------------------------------
  29. // Folder Structure (if kept as separate files):
  30. //
  31. // observer/
  32. // ├── Observer.java
  33. // ├── RegistrationSubject.java
  34. // ├── BatchCreator.java
  35. // ├── EmailService.java
  36. // ├── SlackNotification.java
  37. // └── ObserverDemo.java
  38. // ==================================================
  39.  
  40. import java.util.ArrayList;
  41. import java.util.List;
  42.  
  43. // ==================================================
  44. // File: Observer.java
  45. // Observer Interface
  46. // All subscribers must implement this
  47. // ==================================================
  48. interface Observer {
  49. void update(String studentName, String eventType);
  50. }
  51.  
  52. // ==================================================
  53. // File: RegistrationSubject.java
  54. // Subject (Publisher)
  55. // Maintains list of observers and notifies them when an event occurs
  56. // ==================================================
  57. class RegistrationSubject {
  58. private final List<Observer> observers = new ArrayList<>();
  59. private String studentName;
  60.  
  61. public void addObserver(Observer observer) {
  62. observers.add(observer);
  63. }
  64.  
  65. public void removeObserver(Observer observer) {
  66. observers.remove(observer);
  67. }
  68.  
  69. private void notifyObservers(String eventType) {
  70. for (Observer observer : observers) {
  71. observer.update(studentName, eventType);
  72. }
  73. }
  74.  
  75. public void registerStudent(String studentName) {
  76. this.studentName = studentName;
  77. System.out.println("Student registered: " + studentName);
  78. notifyObservers("STUDENT_REGISTERED");
  79. }
  80. }
  81.  
  82. // ==================================================
  83. // File: BatchCreator.java
  84. // Concrete Observer 1
  85. // ==================================================
  86. class BatchCreator implements Observer {
  87. @Override
  88. public void update(String studentName, String eventType) {
  89. if ("STUDENT_REGISTERED".equals(eventType)) {
  90. System.out.println("[BatchCreator] Assigned batch to " + studentName);
  91. }
  92. }
  93. }
  94.  
  95. // ==================================================
  96. // File: EmailService.java
  97. // Concrete Observer 2
  98. // ==================================================
  99. class EmailService implements Observer {
  100. @Override
  101. public void update(String studentName, String eventType) {
  102. if ("STUDENT_REGISTERED".equals(eventType)) {
  103. System.out.println("[EmailService] Sent welcome email to " + studentName);
  104. }
  105. }
  106. }
  107.  
  108. // ==================================================
  109. // File: SlackNotification.java
  110. // Concrete Observer 3
  111. // ==================================================
  112. class SlackNotification implements Observer {
  113. @Override
  114. public void update(String studentName, String eventType) {
  115. if ("STUDENT_REGISTERED".equals(eventType)) {
  116. System.out.println("[SlackNotification] Sent Slack invite to " + studentName);
  117. }
  118. }
  119. }
  120.  
  121. // ==================================================
  122. // File: ObserverDemo.java
  123. // Client / Usage
  124. // (public removed so it can compile in the same file)
  125. // ==================================================
  126. class ObserverDemo {
  127. public static void main(String[] args) {
  128. RegistrationSubject registration = new RegistrationSubject();
  129.  
  130. Observer batchCreator = new BatchCreator();
  131. Observer emailService = new EmailService();
  132. Observer slack = new SlackNotification();
  133.  
  134. registration.addObserver(batchCreator);
  135. registration.addObserver(emailService);
  136. registration.addObserver(slack);
  137.  
  138. registration.registerStudent("Sai Harsha");
  139.  
  140. System.out.println("\n--- Removing Email Service ---");
  141. registration.removeObserver(emailService);
  142.  
  143. registration.registerStudent("Another Student");
  144. }
  145. }
Success #stdin #stdout 0.1s 35696KB
stdin
Standard input is empty
stdout
Student registered: Sai Harsha
[BatchCreator] Assigned batch to Sai Harsha
[EmailService] Sent welcome email to Sai Harsha
[SlackNotification] Sent Slack invite to Sai Harsha

--- Removing Email Service ---
Student registered: Another Student
[BatchCreator] Assigned batch to Another Student
[SlackNotification] Sent Slack invite to Another Student