Java Reference
In-Depth Information
if(direction.equals("south")) {
nextRoom = currentRoom.getExit("south");
}
if(direction.equals("west")) {
nextRoom = currentRoom.getExit("west");
}
Instead, this whole code segment can now be replaced with:
Room nextRoom = currentRoom.getExit(direction);
Exercise 6.6 Make the changes we have described to the Room and Game classes.
Exercise 6.7 Make a similar change to the printLocationInfo method of Game so that
details of the exits are now prepared by the Room rather than the Game . Define a method in
Room with the following signature:
/**
* Return a description of the room's exits,
* for example, "Exits: north west".
* @return A description of the available exits.
*/
public String getExitString()
So far, we have not changed the representation of the exits in the Room class. We have only
cleaned up the interface. The change in the Game class is minimal—instead of an access of a
public field, we use a method call—but the gain is dramatic. We can now make a change to
the way exits are stored in the room, without any need to worry about breaking anything in
the Game class. The internal representation in Room has been completely decoupled from the
interface. Now that the design is the way it should have been in the first place, exchanging the
separate exit fields for a HashMap is easy. The changed code is shown in Code 6.5.
Code 6.5
Source code of the
Room class
import java.util.HashMap;
// class comment omitted
public class Room
{
private String description;
private HashMap<String, Room> exits;
/**
* Create a room described "description "Initially, it
* has no exits. "description" is something like "a
* kitchen" or "an open courtyard".
*/
Search WWH ::




Custom Search