Command: choosing the operation at run-time : Command Pattern « Design Pattern « Java Tutorial






import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

interface Command {
  void execute();
}

class NewDocument implements Command {
  public void execute() {
    System.out.print("NewDocument ");
  }
}

class SaveDocument implements Command {
  public void execute() {
    System.out.print("SaveDocument! ");
  }
}

class UpdateDocument implements Command {
  public void execute() {
    System.out.print("UpdateDocument");
  }
}

class Macro {
  private List commands = new ArrayList();

  public void add(Command c) {
    commands.add(c);
  }

  public void run() {
    Iterator it = commands.iterator();
    while (it.hasNext())
      ((Command) it.next()).execute();
  }
}

public class CommandPattern {

  public static void main(String args[]) {

    Macro macro = new Macro();

    macro.add(new NewDocument());
    macro.add(new SaveDocument());
    macro.add(new UpdateDocument());
    macro.run();

  }

}








34.8.Command Pattern
34.8.1.Command: choosing the operation at run-time
34.8.2.Command pattern with invoker and receiver