Command Pattern
Author: Deron Eriksson
Description: This Java tutorial describes the command pattern, a behavioral object pattern.
Tutorial created using: Windows Vista || JDK 1.6.0_11 || Eclipse JEE Ganymede SR1 (Eclipse 3.4.1)


Page: < 1 2

(Continued from page 1)

MealInvoker is the invoker class. It contains a reference to the Command to invoke. Its invoke() method calls the execute() method of the Command.

MealInvoker.java

package com.cakes;

public class MealInvoker {

	Command command;

	public MealInvoker(Command command) {
		this.command = command;
	}

	public void setCommand(Command command) {
		this.command = command;
	}

	public void invoke() {
		command.execute();
	}

}

The Demo class demonstrates the command pattern. It instantiates a Lunch (receiver) object and creates a LunchCommand (concrete command) with the Lunch. The LunchCommand is referenced by a Command interface reference. Next, we perform the same procedure on the Dinner and DinnerCommand objects. After this, we create a MealInvoker object with lunchCommand, and we call the invoke() method of mealInvoker. After this, we set mealInvoker's command to dinnerCommand, and once again call invoke() on mealInvoker.

Demo.java

package com.cakes;

public class Demo {

	public static void main(String[] args) {

		Lunch lunch = new Lunch(); // receiver
		Command lunchCommand = new LunchCommand(lunch); // concrete command

		Dinner dinner = new Dinner(); // receiver
		Command dinnerCommand = new DinnerCommand(dinner); // concrete command

		MealInvoker mealInvoker = new MealInvoker(lunchCommand); // invoker
		mealInvoker.invoke();

		mealInvoker.setCommand(dinnerCommand);
		mealInvoker.invoke();

	}

}

The console output of the execution of Demo is shown here.

Console Output

Lunch is being made
Dinner is being made

As you can see, the invoker invokes a command, but has no direct knowledge of the action being performed by the receiver.

Page: < 1 2


Related Tutorials: