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 >

The command pattern is a behavioral object design pattern. In the command pattern, a Command interface declares a method for executing a particular action. Concrete Command classes implement the execute() method of the Command interface, and this execute() method invokes the appropriate action method of a Receiver class that the Concrete Command class contains. The Receiver class performs a particular action. A Client class is responsible for creating a Concrete Command and setting the Receiver of the Concrete Command. An Invoker class contains a reference to a Command and has a method to execute the Command.

In the command pattern, the invoker is decoupled from the action performed by the receiver. The invoker has no knowledge of the receiver. The invoker invokes a command, and the command executes the appropriate action of the receiver. Thus, the invoker can invoke commands without knowing the details of the action to be performed. In addition, this decoupling means that changes to the receiver's action don't directly affect the invocation of the action.

The command pattern can be used to perform 'undo' functionality. In this case, the Command interface should include an unexecute() method.

Here is an example of the command pattern. We have a Command interface with an execute() method.

Command.java

package com.cakes;

public interface Command {

	public void execute();
	
}

LunchCommand implements Command. It contains a reference to Lunch, a receiver. Its execute() method invokes the appropriate action on the receiver.

LunchCommand.java

package com.cakes;

public class LunchCommand implements Command {

	Lunch lunch;

	public LunchCommand(Lunch lunch) {
		this.lunch = lunch;
	}

	@Override
	public void execute() {
		lunch.makeLunch();
	}

}

The DinnerCommand is similar to LunchCommand. It contains a reference to Dinner, a receiver. Its execute() method invokes the makeDinner() action of the Dinner object.

DinnerCommand.java

package com.cakes;

public class DinnerCommand implements Command {

	Dinner dinner;

	public DinnerCommand(Dinner dinner) {
		this.dinner = dinner;
	}

	@Override
	public void execute() {
		dinner.makeDinner();
	}

}

Lunch is a receiver.

Lunch.java

package com.cakes;

public class Lunch {

	public void makeLunch() {
		System.out.println("Lunch is being made");
	}

}

Dinner is also a receiver.

Dinner.java

package com.cakes;

public class Dinner {

	public void makeDinner() {
		System.out.println("Dinner is being made");
	}

}

(Continued on page 2)

Page:    1 2 >


Related Tutorials: