Observer in Notification System
This program integrates Observer pattern in notification system.
Problem Statement
Write a Java program where NotificationService notifies multiple users.
Source Code
| 1 | import java.util.*; |
| 2 | interface User { void update(String msg); } |
| 3 | class NotificationService { |
| 4 | List<User> users=new ArrayList<>(); |
| 5 | void addUser(User u){ users.add(u); } |
| 6 | void notifyUsers(String msg){ for(User u:users) u.update(msg); } |
| 7 | } |
| 8 | class ConcreteUser implements User { |
| 9 | String name; |
| 10 | ConcreteUser(String n){ name=n; } |
| 11 | public void update(String msg){ System.out.println(name+" received: "+msg); } |
| 12 | } |
| 13 | public class NotificationSystem { |
| 14 | public static void main(String[] args) { |
| 15 | System.out.println("Eduinq Notification System"); |
| 16 | NotificationService ns=new NotificationService(); |
| 17 | ns.addUser(new ConcreteUser("User1")); |
| 18 | ns.addUser(new ConcreteUser("User2")); |
| 19 | ns.notifyUsers("System Update Available"); |
| 20 | } |
| 21 | } |
Program Output
Eduinq Notification System User1 received: System Update Available User2 received: System Update Available
Explanation
NotificationService acts as Subject. - Users act as Observers. - Message broadcast demonstrates Observer in enterprise notification systems. Conclusion: Shows Observer integration in notification system.