Desain Class dengan Java

 Seperti pada hakikat desain, desain class di Java juga berguna agar program kita lebih mudah dipahami, tahan lama, dan fleksibel. “Loose Coupling, High Cohesion” merupakan prinsip developer dalam membuat sebuah software.

Coupling (kopling) adalah derajat ketergantungan suatu class terhadapa class lainnya. Loose Copling bertujuan agar ketika ada class yang ingin diubah / dihapus, hal tersebut tidak akan terlalu mempengaruhi class yang lain.

Sedangkan Cohesion (kohesi) adalah keterikatan antar fungsi dalam sebuah class. High Cohesion berguna agar method dalam class tersebut memiliki fungsi yang serupa untuk satu tanggung jawab.

Desain class yang tidak baik biasanya dapat dibuat dalam waktu yang singkat, tapi untuk kedepannya desain tersebut tidak akan bias bertahan lama karena desain yang tidak baik (tidak fleksibel) akan kalah dengan software dengan desain yang baik karena akan sering mengalami pembaharuan serta pembenahan bug.

Untuk itu, kali ini kita akan mencoba membuat sebuah game yang bernama “World of Zuul”, yang terdiri dari beberapa class:


Dengan source code Class Game:

1.  /**

2.   * Class ini membuat dan menginialisasi semua hal

3.   * Class ini membuat semua room, parser, serta memulai game

4.   * Class ini juga mengevaluasi commands yang direturn parser

5.   *

6.   * @author Aufi Fillah

7.   * @version 1.0

8.   */

9.  public class Game

10. {

11.     private Parser parser;

12.     private Room currentRoom;

13.        

14.     /**

15.      * Create the game and initialise its internal map.

16.      */

17.     public Game()

18.     {

19.         createRooms();

20.         parser = new Parser();

21.     }

22.  

23.     /**

24.      * Create all the rooms and link their exits together.

25.      */

26.     private void createRooms()

27.     {

28.         Room outside, theater, pub, lab, office;

29.      

30.         // create the rooms

31.         outside = new Room("outside the main entrance of the university");

32.         theater = new Room("in a lecture theater");

33.         pub = new Room("in the campus pub");

34.         lab = new Room("in a computing lab");

35.         office = new Room("in the computing admin office");

36.        

37.         // initialise room exits

38.         outside.setExits(null, theater, lab, pub);

39.         theater.setExits(null, null, null, outside);

40.         pub.setExits(null, outside, null, null);

41.         lab.setExits(outside, office, null, null);

42.         office.setExits(null, null, null, lab);

43.  

44.         currentRoom = outside;  // start game outside

45.     }

46.  

47.     /**

48.      *  Main play routine.  Loops until end of play.

49.      */

50.     public void play()

51.     {            

52.         printWelcome();

53.  

54.         // Enter the main command loop.  Here we repeatedly read commands and

55.         // execute them until the game is over.

56.                

57.         boolean finished = false;

58.         while (! finished) {

59.             Command command = parser.getCommand();

60.             finished = processCommand(command);

61.         }

62.         System.out.println("Thank you for playing.  Good bye.");

63.     }

64.  

65.     /**

66.      * Print out the opening message for the player.

67.      */

68.     private void printWelcome()

69.     {

70.         System.out.println();

71.         System.out.println("Welcome to the World of Zuul!");

72.         System.out.println("World of Zuul is a new, incredibly boring adventure game.");

73.         System.out.println("Type 'help' if you need help.");

74.         System.out.println();

75.         System.out.println("You are " + currentRoom.getDescription());

76.         System.out.print("Exits: ");

77.         if(currentRoom.northExit != null) {

78.             System.out.print("north ");

79.         }

80.         if(currentRoom.eastExit != null) {

81.             System.out.print("east ");

82.         }

83.         if(currentRoom.southExit != null) {

84.             System.out.print("south ");

85.         }

86.         if(currentRoom.westExit != null) {

87.             System.out.print("west ");

88.         }

89.         System.out.println();

90.     }

91.  

92.     /**

93.      * Given a command, process (that is: execute) the command.

94.      * @param command The command to be processed.

95.      * @return true If the command ends the game, false otherwise.

96.      */

97.     private boolean processCommand(Command command)

98.     {

99.         boolean wantToQuit = false;

100.   

101.          if(command.isUnknown()) {

102.              System.out.println("I don't know what you mean...");

103.              return false;

104.          }

105.   

106.          String commandWord = command.getCommandWord();

107.          if (commandWord.equals("help")) {

108.              printHelp();

109.          }

110.          else if (commandWord.equals("go")) {

111.              goRoom(command);

112.          }

113.          else if (commandWord.equals("quit")) {

114.              wantToQuit = quit(command);

115.          }

116.   

117.          return wantToQuit;

118.      }

119.   

120.      // implementations of user commands:

121.   

122.      /**

123.       * Print out some help information.

124.       * Here we print some stupid, cryptic message and a list of the

125.       * command words.

126.       */

127.      private void printHelp()

128.      {

129.          System.out.println("You are lost. You are alone. You wander");

130.          System.out.println("around at the university.");

131.          System.out.println();

132.          System.out.println("Your command words are:");

133.          System.out.println("   go quit help");

134.      }

135.   

136.      /**

137.       * Try to go in one direction. If there is an exit, enter

138.       * the new room, otherwise print an error message.

139.       */

140.      private void goRoom(Command command)

141.      {

142.          if(!command.hasSecondWord()) {

143.              // if there is no second word, we don't know where to go...

144.              System.out.println("Go where?");

145.              return;

146.          }

147.   

148.          String direction = command.getSecondWord();

149.   

150.          // Try to leave current room.

151.          Room nextRoom = null;

152.          if(direction.equals("north")) {

153.              nextRoom = currentRoom.northExit;

154.          }

155.          if(direction.equals("east")) {

156.              nextRoom = currentRoom.eastExit;

157.          }

158.          if(direction.equals("south")) {

159.              nextRoom = currentRoom.southExit;

160.          }

161.          if(direction.equals("west")) {

162.              nextRoom = currentRoom.westExit;

163.          }

164.   

165.          if (nextRoom == null) {

166.              System.out.println("There is no door!");

167.          }

168.          else {

169.              currentRoom = nextRoom;

170.              System.out.println("You are " + currentRoom.getDescription());

171.              System.out.print("Exits: ");

172.              if(currentRoom.northExit != null) {

173.                  System.out.print("north ");

174.              }

175.              if(currentRoom.eastExit != null) {

176.                  System.out.print("east ");

177.              }

178.              if(currentRoom.southExit != null) {

179.                  System.out.print("south ");

180.              }

181.              if(currentRoom.westExit != null) {

182.                  System.out.print("west ");

183.              }

184.              System.out.println();

185.          }

186.      }

187.   

188.      /**

189.       * "Quit" was entered. Check the rest of the command to see

190.       * whether we really quit the game.

191.       * @return true, if this command quits the game, false otherwise.

192.       */

193.      private boolean quit(Command command)

194.      {

195.          if(! command.hasSecondWord()) {

196.              System.out.println("Quit what?");

197.              return false;

198.          }

199.          else {

200.              return true;  // signal that we want to quit

201.          }

202.      }

203.  }

 

Class Game merupakan main class dari game ini. Class ini mengatur keperluan game kemudian masuk kedalam loop untuk membaca dan mengeksekeusi commands. Class ini juga berisi code yang mengimplementasikan setiap user commands.

Lalu ada Class CommandWords dengan source code:

1.  /**

2.   * Class ini menyimpan daftar semua command words

3.   * di dalam game

4.   * Class ini digunakan untuk mengetahui commands ketika user

5.   * mengetik

6.   *

7.   * @author (your name)

8.   * @version (a version number or a date)

9.   */

10. public class CommandWords

11. {

12.     // a constant array that holds all valid command words

13.     private static final String[] validCommands = {

14.         "go", "quit", "help"

15.     };

16.  

17.     /**

18.      * Constructor - initialise the command words.

19.      */

20.     public CommandWords()

21.     {

22.         // nothing to do at the moment...

23.     }

24.  

25.     /**

26.      * Check whether a given String is a valid command word.

27.      * @return true if a given string is a valid command,

28.      * false if it isn't.

29.      */

30.     public boolean isCommand(String aString)

31.     {

32.         for(int i = 0; i < validCommands.length; i++) {

33.             if(validCommands[i].equals(aString))

34.                 return true;

35.         }

36.         // if we get here, the string was not found in the commands

37.         return false;

38.     }

39. }

 

Class CommandWords mendefinisikan semua command yang valid dalalm game, yang dilakukan dengan menyimpan sebuah array of String object yang merepresentasikan command words.

Setelah itu terdapat Class Command dengan source code:

1.  /**

2.   * Class yang menyimpan informasi tentang command yang

3.   * diinput user

4.   * Command berisi 2 word, word pertama berupa perintah dan

5.   * word kedua adalah isi perintah

6.   *

7.   * @author Aufi Fillah

8.   * @version 1.0

9.   */

10. public class Command

11. {

12.     private String commandWord;

13.     private String secondWord;

14.  

15.     /**

16.      * Create a command object. First and second word must be supplied, but

17.      * either one (or both) can be null.

18.      * @param firstWord The first word of the command. Null if the command

19.      *                  was not recognised.

20.      * @param secondWord The second word of the command.

21.      */

22.     public Command(String firstWord, String secondWord)

23.     {

24.         commandWord = firstWord;

25.         this.secondWord = secondWord;

26.     }

27.  

28.     /**

29.      * Return the command word (the first word) of this command. If the

30.      * command was not understood, the result is null.

31.      * @return The command word.

32.      */

33.     public String getCommandWord()

34.     {

35.         return commandWord;

36.     }

37.  

38.     /**

39.      * @return The second word of this command. Returns null if there was no

40.      * second word.

41.      */

42.     public String getSecondWord()

43.     {

44.         return secondWord;

45.     }

46.  

47.     /**

48.      * @return true if this command was not understood.

49.      */

50.     public boolean isUnknown()

51.     {

52.         return (commandWord == null);

53.     }

54.  

55.     /**

56.      * @return true if the command has a second word.

57.      */

58.     public boolean hasSecondWord()

59.     {

60.         return (secondWord != null);

61.     }

62. }

 

Class Command merepresentasikan sebuah command yang telah diinput oleh user dan mengecek apakah inputan tersebut valid atau tidak serta juga berguna untuk mengambil word pertama dan kedua dari commands.

Lalu ada Class Parser dengan source code:

1.  import java.util.Scanner;

2.  import java.io.BufferedReader;

3.  import java.io.InputStreamReader;

4.  import java.util.StringTokenizer;

5.  /**

6.   * Class ini membaca user input dan mencoba mendefinisikannya

7.   * sebagai "Adventure" command.

8.   *

9.   * @author Aufi Fillah

10.  * @version 1.0

11.  */

12. public class Parser

13. {

14.     private CommandWords commands;  // holds all valid command words

15.     private Scanner reader;         // source of command input

16.  

17.     /**

18.      * Create a parser to read from the terminal window.

19.      */

20.     public Parser()

21.     {

22.         commands = new CommandWords();

23.         reader = new Scanner(System.in);

24.     }

25.  

26.     /**

27.      * @return The next command from the user.

28.      */

29.     public Command getCommand()

30.     {

31.         String inputLine;   // will hold the full input line

32.         String word1 = null;

33.         String word2 = null;

34.  

35.         System.out.print("> ");     // print prompt

36.  

37.         inputLine = reader.nextLine();

38.  

39.         // Find up to two words on the line.

40.         Scanner tokenizer = new Scanner(inputLine);

41.         if(tokenizer.hasNext()) {

42.             word1 = tokenizer.next();      // get first word

43.             if(tokenizer.hasNext()) {

44.                 word2 = tokenizer.next();      // get second word

45.                 // note: we just ignore the rest of the input line.

46.             }

47.         }

48.  

49.         // Now check whether this word is known. If so, create a command

50.         // with it. If not, create a "null" command (for unknown command).

51.         if(commands.isCommand(word1)) {

52.             return new Command(word1, word2);

53.         }

54.         else {

55.             return new Command(null, word2);

56.         }

57.     }

58. }

 

Class Parser membaca sebuah line input dari terminal dan mencoba untuk mengkategorikannya sebagai command. Class ini juga membuat object of class Command yang merepresentasikan command yang diinput.

Yang terakhir ada Class Room dengan source code:

1.  /**

2.   * Class yang merepresentasikan sebuah lokasi dalam game

3.   *

4.   * @author Aufi Fillah

5.   * @version 1.0

6.   */

7.  public class Room

8.  {

9.      public String description;

10.     public Room northExit;

11.     public Room southExit;

12.     public Room eastExit;

13.     public Room westExit;

14.  

15.     /**

16.      * Create a room described "description". Initially, it has

17.      * no exits. "description" is something like "a kitchen" or

18.      * "an open court yard".

19.      * @param description The room's description.

20.      */

21.     public Room(String description)

22.     {

23.         this.description = description;

24.     }

25.  

26.     /**

27.      * Define the exits of this room.  Every direction either leads

28.      * to another room or is null (no exit there).

29.      * @param north The north exit.

30.      * @param east The east east.

31.      * @param south The south exit.

32.      * @param west The west exit.

33.      */

34.     public void setExits(Room north, Room east, Room south, Room west)

35.     {

36.         if(north != null)

37.             northExit = north;

38.         if(east != null)

39.             eastExit = east;

40.         if(south != null)

41.             southExit = south;

42.         if(west != null)

43.             westExit = west;

44.     }

45.  

46.     /**

47.      * @return The description of the room.

48.      */

49.     public String getDescription()

50.     {

51.         return description;

52.     }

53.  

54. }

 

Class ini merepresentasikan lokasi dalam game yang memiliki jalan keluar yang akan mengarah ke room lainnya.

Apabila kita membuat new Game() dari Class Game dan menjalankan void play(), program akan menampilkan kalimat pembuka:


Sekarang kita sedang berada di main entrance of the university dan kita memiliki opsi ingin pergi kea rah mana. Mari kita coba pergi kearah east, dan program akan menampilkan:


Ini terjadi karena kita sudah mendesain program agar user menginputkan 2 kata dengan susuan “command” + “value”. Mari kita coba menginput “help” untuk mengetahui beberapa commands yang tersedia.


Setelah itu, mari kita coba lagi pergi  berkeliling dengan menggunakan command go.


Lalu, apabila kita menginput arah yang tidak memiliki jalan program akan mengoutput:


Dan apabila kita ingin keluar dari game ini, kita harus menginput “quit”. Akan tetapi, yang terjadi malah seperti ini:


Desain output seperti ini sangat berguna agar user yang salah memasukkan input tidak akan kebablasan untuk keluar game. Lalu untuk benar-benar ingin keluar dari game kita akan menginput:


Dan program pun berhenti.

Sekian adalah contoh program sederhana desain class dengan menggunakan game “World of Zuul”. Apabila ada kesalah mohon dikoreksi, terimakasih.

Komentar

Postingan populer dari blog ini

Game Java Rapid Roll

ETS PBO (Bagian 1) - membuat Sistem ATM