|
The Command Pattern
An Introduction with Examples in Java |
|
Prof. David Bernstein |
| Computer Science Department |
| bernstdh@jmu.edu |
In UML
Operation an interfaceOperand an interface/**
* A very simple text document used in an example of the Command pattern
*
* @author Prof. David Bernstein, James Madison University
* @version 1.0
*/
public class TextDocument
{
private String text;
/**
* Default Constructor
*/
public TextDocument()
{
text = null;
}
/**
* Get the text
*
* @return The text
*/
public String getText()
{
return text;
}
/**
* Replace all occurences of one word with another
*
* @param oldWord The old word
* @param newWord The new word
*/
public void replace(String oldWord, String newWord)
{
text = text.replaceAll(oldWord, newWord);
}
/**
* Set the text
*
* @param text The text
*/
public void setText(String text)
{
this.text = text;
}
}
/**
* A very simple operation used in an example of the Command pattern
*
* @author Prof. David Bernstein, James Madison University
* @version 1.0
*/
public class Replace
{
private boolean applied;
private String newWord, oldWord, savedState;
private TextDocument operand;
/**
* Explicit Value Constructor
*
* @param document The operand of this operation
*
* @param oldWord The old word
* @param newWord The new word
*/
public Replace(TextDocument document, String oldWord, String newWord)
{
operand = document;
applied = false;
this.oldWord = oldWord;
this.newWord = newWord;
}
/**
* Apply this Replace operation
*/
public void apply()
{
savedState = operand.getText();
operand.replace(oldWord, newWord);
applied = true;
}
/**
* Undo this Replace operation
*/
public void undo()
{
if (applied)
{
operand.setText(savedState);
applied = false;
}
}
}
/**
* A simple example of the Command pattern
*
* @author Prof. David Bernstein, James Madison University
* @version 1.0
*/
public class Driver
{
/**
* The entry point
*
* @param args The command-line arguments
*/
public static void main(String[] args)
{
int i;
TextDocument document;
Replace[] replace;
document = new TextDocument();
document.setText("George is a little monkey, "+
"and all monkeys are curious. "+
"But no monkey is as curious "+
"as George.");
System.out.println("\n"+document.getText()+"\n");
replace = new Replace[3];
replace[0] = new Replace(document,"curious","power hungry");
replace[1] = new Replace(document,"monkey", "President");
replace[2] = new Replace(document,"little", "U.S.");
for (i=0; i < replace.length; i++) {
replace[i].apply();
System.out.println("\n"+document.getText()+"\n");
}
for (i=replace.length-1; i >= 0; i--) {
replace[i].undo();
System.out.println("\n"+document.getText()+"\n");
}
}
}