| CSC 207 | Algorithms and Object Oriented Design | Spring 2011 |
Summary: In this lab, you will get a concrete look at a brief motivating example of the state pattern.
/** A class that prints out messages of various types in several
* languages.
*
* @author Jerod Weinman
*/
public class MultiLingualMessages {
/**
* An enumerated type explicitly listing the possible languages.
*/
public enum Language {English, French, Spanish, Chef};
/** Object member representing the language */
private Language lang;
/** Return the language of this object.
*
* @return the language of this object
*/
public Language getLanguage() { return lang; }
/** Set the language of this object. */
public void setLanguage(Language lang) {
this.lang = lang;
}
/** Print a question in the appropriate language */
public void printQuestion() {
String msg = "";
switch(lang) {
case English: msg = "What?"; break;
case Spanish:
case French: msg = "Que?"; break;
case Chef: msg = "Bork?"; break;
default: throw new IllegalStateException("Unknown current language.");
}
System.out.println(msg);
}
/** Print an exclamation in the appropriate language */
public void printExclamation() {
String msg = "";
switch(lang) {
case English: msg = "Whoah!"; break;
case Spanish: msg = "¡Caramba!"; break;
case French: msg = "Par bleu!"; break;
case Chef: msg = "Bork!"; break;
default: throw new IllegalStateException("Unknown current language.");
}
System.out.println(msg);
}
}
Messenger that has two
operations, one for fetching an exclamation String
and another for fetching the question String. (Note
that your return types should not
be void.)
FrenchMessenger
and ChefMessenger. You only need to write two,
one-line methods for each, and you need no object or class variables.
enum LanguageMultiLingualMessages above, we can
use a Messenger object. Thus, the class below provides a
"context" for a particular messenger, replacing our original
class MultiLingalMessage.
/** A class that prints out messages of various types in several
* languages using the state pattern.
*
* @author Jerod Weinman
* @author YOUR NAME HERE
*/
public class MessengerContext
{
private Messenger messenger;
/**
* Set the messenger for this context to the specified value.
*
* @param msgr the specified value to use for this context.
*/
public void setMessenger(Messenger msgr)
{
messenger = msgr;
}
/** Print a question using the messenger state of this context. */
public void printQuestion()
{
// BODY HERE
}
/** Print an exclamation using the current messenger state of this context. */
public void printExclamation()
{
// BODY HERE
}
}
Messenger interface.
MultiLingualMessages?