今日目標,記錄使用者的狀態。
先描述使用者的畫面和可操作功能
這時候請讀者根據上方的情景試想一些狀況:
如果紀錄每個使用者的狀態,就可以在使用者在發生上述的情況時,做出對應的處理(比如禁止他到那個頁面),我們要記錄的狀態資訊包含:
因此,我們要再建立一個實例幫忙儲存這些資訊:
package com.example.room;
import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Getter @Setter
class Status {
private boolean inRoom = false;
private String roomId = "";
private boolean ready = false;
}
@Component
public class UserStatus {
Map<String, Status> userStatus = new HashMap<>();
public void setUserInRoom(String username, boolean isInRoom) {
this.userStatus.get(username).setInRoom(isInRoom);
}
public boolean isUserInRoom(String username) {
return this.userStatus.get(username).isInRoom();
}
public void setUserRoomId(String username, String roomId) {
this.userStatus.get(username).setRoomId(roomId);
}
public String getUserRoomId(String username) {
return this.userStatus.get(username).getRoomId();
}
public void setUserReady(String username, boolean isReady) {
this.userStatus.get(username).setReady(isReady);
}
public boolean isUserReady(String username) {
return this.userStatus.get(username).isReady();
}
public boolean containsUser(String username) {
return this.userStatus.containsKey(username);
}
public void initialize(String username) {
this.userStatus.put(username, new Status());
}
}
其實應該在昨天寫的,但今天才想到
(同樣的,小弟不確定是否需要一個 Service 負責存取這個實例)