gpt4 book ai didi

java - java中通过流实现对象的多态性?

转载 作者:行者123 更新时间:2023-11-30 07:19:16 25 4
gpt4 key购买 nike

我正在为一个大学项目编写代码。我们必须实现一款可以远程多人玩的棋盘游戏。

我们目前使用请求-响应模式:客户端通过 IO 流向服务器发送请求,服务器分析它们并返回正确的响应。

问题是我们有多种类型的请求,我们使用多态性来了解收到的是哪个请求:

/**
* This method is only functional to polymorphism: it should never be invoked.
* @param request
* @return only an assertion error
*/
public ResponseMsg handleRequest(RequestMsg request) {

throw new AssertionError("It was created a RequestMsg. This should never happen.\n"
}

/**
* The request is to change the map.
* If the game is not started and the player is the first, the map will be changed and
* a broadcast with the new map will be sent to all the players.
* @param request: the request containing the name of the map chosen
* @return An ack response message
*/
public ResponseMsg handleRequest(ChangeMapRequestMsg request) {

if (game != null)
return new InvalidRequestMsg("You can't change the map when the game is already started");

else if (request.getToken().getPlayerNumber() != 0)
return new InvalidRequestMsg("Only the first player can change the map");

else {

this.map = request.getMap();

BroadcastMsg broadcast = new ChangedMapBroadcastMsg(request.getMap());
publisherInterface.publish(broadcast, getLobby());

return new AckResponseMsg("Map changed successfully");
}
}

/**
* Handles a chat message
* it sends a broadcast containing the message to all the players and an
* acknowledgement to the player who sent it
*
* @param the chat request from the player
* @return the acknowledgement
*/
public ResponseMsg handleRequest(SendChatRequestMsg request) {

ChatBroadcastMsg chatBroadcast = new ChatBroadcastMsg(players.indexOf(request.getToken()), request.getMessage());
publisherInterface.publish(chatBroadcast, getLobby());
return new AckResponseMsg("Chat message sent.");
}

问题是,当我们向服务器发送请求时,我们需要通过输出流传递它们,服务器将通过输入流读取它们。我们被迫将它们转换为Object,因此我们失去了利用多态性的可能性。

我们如何保持利用多态性的能力?我们不想使用 instanceof 来获取请求的动态类型,因为我们的教授告诉我们永远不要这样做。

最佳答案

您需要做的是检查通过流发送的对象是否是某个类的实例,然后将该对象强制转换为该类。

Object obj = ...; // The object sent over the stream
if(obj instanceof String) {
String str = (String) obj; // Cast it to String
...
} else if(obj instanceof Integer) {
Integer i = (Integer) obj; // Cast it to Integer
...
}

因此,如果我要通过流发送一个 String 对象,第一个 if 语句将运行。

关于java - java中通过流实现对象的多态性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37856996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com