public abstract class User { private IChatRoom chartroom; private String userId; private String userName; public User(IChatRoom room, String userId, String userName) { this.chartroom = room;//用户选择聊天室 this.userId = userId; this.userName = userName; } public abstract void sendMessage(String msg, String userId); public abstract void receiveMessage(String msg); public String getUserId() { return userId; } public String getUserName() { return userName; } public IChatRoom getChartroom() { return chartroom; } } public class ChartUser extends User { public ChartUser(IChatRoom room, String userId, String userName) { super(room, userId, userName); } @Override public void sendMessage(String msg, String userId) { System.out.println(this.getUserName()+" send message:"+msg); this.getChartroom().sendMessage(msg,userId); } @Override public void receiveMessage(String msg) { System.out.println(this.getUserName()+" receive message:"+msg); } } public interface IChatRoom { void sendMessage(String msg,String userId); void addUser(User user); } public class ChartUser extends User { public ChartUser(IChatRoom room, String userId, String userName) { super(room, userId, userName); } @Override public void sendMessage(String msg, String userId) { System.out.println(this.getUserName()+" send message:"+msg); this.getChartroom().sendMessage(msg,userId); } @Override public void receiveMessage(String msg) { System.out.println(this.getUserName()+" receive message:"+msg); } } //测试 public class Client { public static void main(String[] args){ IChatRoom chatRoom = new ChatRoom(); //初始化用户 User userA = new ChartUser(chatRoom,"A","USERA"); User userB = new ChartUser(chatRoom,"B","USERB"); //用户注册到中介 chatRoom.addUser(userA); chatRoom.addUser(userB); //模拟发送消息 userA.sendMessage("Hello","B"); System.out.println("********************"); userB.sendMessage("Hello","A"); } }
原文:https://www.cnblogs.com/camcay/p/12379936.html