【发布时间】:2017-06-21 03:19:41
【问题描述】:
我正在使用 Java 为服务器构建一个多人游戏。目前,我正在使用单个类文件来存储播放器数据并处理数据。我是初学者,所以我不知道这是一个不好的做法。 http://howtodoinjava.com/best-practices/5-class-design-principles-solid-in-java/这篇文章让我明白我违反了“单一责任原则”的规则。
这就是我的代码现在的样子。
public class PlayerSession{
String playerId;
String playerName;
// 20+ player data fields, which I am trying to reduce
// and keep only the most used data
public void messageProcessor(JSONObject clientRequest) throws JSONException{
switch(clientRequest.getString("task")){
case "login": loginProcess(); break;
case "logout": logoutProcess(); break;
//50+ different actions
}
}
public void populateSessionData(String playerId){
// populate player data from database
}
private void loginProcess(){
//Process login
}
private void logoutProcess(){
//Process logout
}
//20+ other methods which do entirely different tasks.
}
随着我们添加更多功能,该类将变得极其难以维护和修改。现在我试图将这个类解耦成两个不同的类。一个,仅用于存储玩家数据,另一个用于处理行为,如下所示。
public class PlayerSession {
final TaskHandler taskHandler = new TaskHandler();
public void messageProcessor(JSONObject clientRequest) throws JSONException {
switch (clientRequest.getString("task")) {
case "login":
taskHandler.loginProcess();
break;
case "logout":
taskHandler.logoutProcess();
break;
// 50+ different actions
}
}
}
public class PlayerData {
String playerId;
String playerName;
// 20+ player data fields, which I am trying to reduce
// and keep only the most used data
public void populateSessionData(String playerId) {
// populate player data from database
}
}
public class TaskHandler {
final PlayerData player = new PlayerData();
private void loginProcess() {
// Process login
}
private void logoutProcess() {
// Process logout
}
// 20+ other methods which do entirely different tasks.
}
这种设计导致为单个客户端创建 2 个额外的对象,即 PlayerData 和 TaskHandler。对于 10,000 个并发客户端的服务器,这会成为问题吗?这是正确的方法吗?如果不是,对于这种情况,最好的方法是什么?
在某处我读到对象只是为了保存数据不是一个好方法。对吗?
【问题讨论】:
-
你在使用spring之类的框架吗?
-
@AshutoshJha 我正在使用 netty 和 websockets。这不是基于 REST 的应用程序。这是一个需要全双工实时通信的网络应用程序。
标签: java oop class-design