Chat system
unknown
java
a month ago
2.5 kB
1
Indexable
Never
import java.util.HashSet; import java.util.Set; // Interface Definitions interface User { String getUsername(); void sendMessage(String message, ChatSession session); void receiveMessage(String message); } interface Message { String getContent(); User getSender(); User getReceiver(); } interface ChatSession { void addUser(User user); void removeUser(User user); void sendMessage(User sender, String message); } // Implementation Classes class ChatUser implements User { private String username; public ChatUser(String username) { this.username = username; } @Override public String getUsername() { return username; } @Override public void sendMessage(String message, ChatSession session) { session.sendMessage(this, message); } @Override public void receiveMessage(String message) { System.out.println(username + " received message: " + message); } } class ChatMessage implements Message { private String content; private User sender; private User receiver; public ChatMessage(String content, User sender, User receiver) { this.content = content; this.sender = sender; this.receiver = receiver; } @Override public String getContent() { return content; } @Override public User getSender() { return sender; } @Override public User getReceiver() { return receiver; } } class SimpleChatSession implements ChatSession { private Set<User> users = new HashSet<>(); @Override public void addUser(User user) { users.add(user); } @Override public void removeUser(User user) { users.remove(user); } @Override public void sendMessage(User sender, String message) { for (User user : users) { if (!user.equals(sender)) { user.receiveMessage(sender.getUsername() + ": " + message); } } } } // Main Application public class ChatApplication { public static void main(String[] args) { // Create users User alice = new ChatUser("Alice"); User bob = new ChatUser("Bob"); // Create a chat session ChatSession session = new SimpleChatSession(); session.addUser(alice); session.addUser(bob); // Users send messages alice.sendMessage("Hi Bob!", session); bob.sendMessage("Hello Alice!", session); } }
Leave a Comment