[英]How do I create a manager class to hold certain variables without abusing static?
Java n00b 在這里。 我正在為 Minecraft 服務器制作一個插件,我想使用一個類來保存插件的所有變量:
public class BwMgr {
Boolean enabled = false;
final HashSet<Player> red = new HashSet<>();
final HashSet<Player> green = new HashSet<>();
final HashSet<Player> blue = new HashSet<>();
final HashSet<Player> orange = new HashSet<>();
final HashSet<Player> purple = new HashSet<>();
final HashSet<Player> yellow = new HashSet<>();
final HashSet<Player> black = new HashSet<>();
final HashSet<Player> white = new HashSet<>();
public void assignTeams() {
}
}
每個 HashSet 都應該包含玩家團隊。 其他類將訪問布爾值以確定插件是否已啟用:
public class BwListener implements Listener {
private final BwMgr bwMgr = new BwMgr();
@EventHandler
public void onPlayerJoinEvent(PlayerJoinEvent e) {
if (bwMgr.enabled) {
// do stuff
}
}
}
應在此處更新enabled
:
public class BwCmd implements CommandExecutor {
private BwMgr bwMgr = new BwMgr();
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("bw")) {
if (args[0].equalsIgnoreCase("enable")) {
bwMgr.enabled = true;
} else if (args[0].equalsIgnoreCase("disable")) {
bwMgr.enabled = false;
}
}
return false;
}
}
當然,由於每個類使用BwMgr
的不同實例,它們使用不同版本的 Boolean enabled
。 我可以將static
放在BwMgr
的所有內容前面,但我覺得那會是一種濫用。 任何想法將不勝感激。
您需要通過 BwCmd 和 BwListener 的構造函數傳遞BwMgr
的相同實例。
所以在 BwCmd 中應該是這樣的:
public class BwCmd implements CommandExecutor {
private BwMgr bwMgr;
// Pass through the constructor an instance of BwMgr.
public BwCmd(BwMgr bwMgr) {
this.bwMgr = bwMgr;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("bw")) {
if (args[0].equalsIgnoreCase("enable")) {
bwMgr.enabled = true;
} else if (args[0].equalsIgnoreCase("disable")) {
bwMgr.enabled = false;
}
}
return false;
}
}
BwListener 類:
public class BwListener implements Listener {
private final BwMgr bwMgr;
// Pass through the constructor an instance of BwMgr.
public BwListener(BwMgr bwMgr) {
this.bwMgr = bwMgr;
}
@EventHandler
public void onPlayerJoinEvent(PlayerJoinEvent e) {
if (bwMgr.enabled) {
// do stuff
}
}
}
在你的主課中:
// Create one instance of bwMgr.
BwMgr bwMgr = new BwMgr();
// Initialize BwListener and BwCmd with the same BwMgr.
BwListener bwListener = new BwListener(bwMgr);
BwCmd bwCmd = new BwCmd(bwMgr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.