Right now, if we have 20 different classes that extend Item, and they all handle the word "examine," they all have kind of the same code:
@Override public String handle(String s) { if (s.equalsIgnoreCase("examine")) { return this.getDescription(); } else { ... } }
This is ruining the point of reusable code. We are writing the same thing over and over.
Now suppose: We create a Command class. Somehow, when the word "examine" goes to the Item's handle(String s) method, the Item "knows" what to do with it, because the Item keeps an instance of the Examine command.
What if we used our old friend HashMap? If each instance of an Item had a HashMap of available commands, with words like "examine," "read," "destroy," "eat" as the keys?
This is going to take some planning.
Right now, if we have 20 different classes that extend Item, and they all handle the word "examine," they all have kind of the same code:
@Override public String handle(String s) { if (s.equalsIgnoreCase("examine")) { return this.getDescription(); } else { ... } }
This is ruining the point of reusable code. We are writing the same thing over and over.
Now suppose: We create a Command class. Somehow, when the word "examine" goes to the Item's handle(String s) method, the Item "knows" what to do with it, because the Item keeps an instance of the Examine command.
What if we used our old friend HashMap? If each instance of an Item had a HashMap of available commands, with words like "examine," "read," "destroy," "eat" as the keys?