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

标签 java polymorphism

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

我们目前使用请求-响应模式:客户端通过 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/

相关文章:

java - 在多线程程序中处理更新 hibernate

c++ - 如何将基类更改为继承类?

c++ - C++ 纯虚函数调用的性能可变性

java - 什么是java中的多态方法?

polymorphism - 属于特征的对象的向量

java - 使用 Java 保存 Word 文件(可运行的 JAR)

java - 如何创建动态组合框作为 JTable 中的编辑器

java - 使用 Java 将电话号码转换为国际格式 (E.164) 的最佳方法是什么?

C++继承与多态

java - Hibernate hql/criteria 结果包含集合