Java Reference
In-Depth Information
Code 6.4
Using an accessor
method to decrease
coupling
public class Room
{
private String description;
private Room northExit;
private Room southExit;
private Room eastExit;
private Room westExit;
// existing methods unchanged
public Room getExit(String direction)
{
if (direction.equals( "north" )) {
return northExit;
}
if (direction.equals( "east" )) {
return eastExit;
}
if (direction.equals( "south" )) {
return southExit;
}
if (direction.equals( "west" )) {
return westExit;
}
return null ;
}
}
Having made this change to the Room class, we need to change the Game class as well.
Wherever an exit variable was accessed, we now use the accessor method. For example,
instead of writing
nextRoom = currentRoom.eastExit;
we now write
nextRoom = currentRoom.getExit("east");
This makes coding one section in the Game class much easier as well. In the goRoom method,
the replacement suggested here will result in the following code segment:
Room nextRoom = null;
if(direction.equals("north")) {
nextRoom = currentRoom.getExit("north");
}
if(direction.equals("east")) {
nextRoom = currentRoom.getExit("east");
}
Search WWH ::




Custom Search