저는 대학 프로젝트 코드를 작성하고 있습니다. 우리는 원격 및 멀티 플레이어에서 재생할 보드 게임을 구현해야합니다.자바에서 스트림을 통한 객체의 다형성?
현재 요청 - 응답 패턴을 사용하고 있습니다. 클라이언트는 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를 기본 요청 클래스 (RequestMsg)로 캐스트 할 수 없습니까? 특정 요청 유형을 알 필요가 없습니다. – Eran
우리는 그렇게했고 호출 된 메서드는 항상 일반적인 메서드 였지만 특정 메서드가 필요했습니다. – Luvi
이 메서드는 모두 같은 클래스에 정의되어 있습니까? 어떤 계급입니까? – Eran