今天面试遇到一个笔试题。
要求如下:
/** * Player对象以username为索引,对象创建后username不会变化 * PlayerManager每隔一分钟会将isOffline()==true 的player对象删除 * 写出单元测试 */ public interface Player { String username(); //向玩家发信息 void write(String message); //玩家是否掉线 boolean isOffline(); }
public interface PlayerManager{ // 添加一个玩家 void add(Player player); //获取一个玩家 Player getPlayer(String username); //广播一个消息 void broadcast(String message); } 请完成代码:
public class PlayerImpl implements Player{ //用户名 private String username; //是否在线 private boolean offline; public PlayerImpl(String username) { this.username = username; } @Override public String username() { return username; } @Override public void write(String message) { System.out.println(this.username+"接收到消息:"+message); } @Override public boolean isOffline() { return offline; } public void setOffline(boolean offline) { this.offline = offline; } }
public class PlayerManagerImpl implements PlayerManager{ static { // 创建一个 Timer 实例 Timer timer = new Timer(); // 创建一个 TimerTask 实例 TimerTask task = new TimerTask() { @Override public void run() { checkPlayer(); } }; // 设置定时任务:延迟1分钟开始执行,然后每隔1分钟执行一次 long delay = 60 * 1000; long period = 60 * 1000; timer.schedule(task, delay, period); } private static final Map<String,Player> playerMap = new ConcurrentHashMap<>(); private static final PlayerManager playerManager = new PlayerManagerImpl(); private PlayerManagerImpl() { } public static PlayerManager getInstance(){ return playerManager; } @Override public void add(Player player) { playerMap.put(player.username(),player); } private static void checkPlayer(){ Collection<Player> values = playerMap.values(); if(CollUtil.isNotEmpty(values)){ for (Player p:values){ if(p.isOffline()){ playerMap.remove(p.username()); } } } } @Override public Player getPlayer(String username) { return playerMap.get(username); } @Override public void broadcast(String message) { Collection<Player> values = playerMap.values(); if(CollUtil.isNotEmpty(values)){ for (Player p:values){ p.write(message); } } } public static void main(String[] args) throws InterruptedException { PlayerManager instance = PlayerManagerImpl.getInstance(); PlayerImpl zhangsan = new PlayerImpl("zhangsan"); instance.add(zhangsan); instance.add(new PlayerImpl("lisi")); instance.add(new PlayerImpl("wangwu")); instance.broadcast("hello"); zhangsan.setOffline(true); Thread.sleep(1000*60); instance.broadcast("aaaa"); } }