Command Pattern

Command Pattern

In Command pattern objects used to represent and encapsulate information that is needed to call operation at later time. This information includes operation name and object that owns method and values for method parameters.

When command pattern used three terms always will be associated with it i.e. client, invoker and receiver. Here client creates new command object and provides all information that is required to call method at later time. Invoker decides when method should be called. Lastly receiver is instance of class that contains actual method code.

In this design pattern command objects makes us easier to build general components that need to delegate, sequence or execute operation calls at time of their choice without knowing anything about who is the owner of method or what are method parameters.

Example:

  • The Command interface
public interface Command {
	void execute();
}

 

  • The Invoker class
import java.util.ArrayList;
import java.util.List;

public class Switch {
	private List<Command> history = new ArrayList<Command>();

	public Switch() {
	}

	public void storeAndExecute(Command cmd) {
		this.history.add(cmd); // optional
		cmd.execute();
	}

}

 

  • The Receiver class
public class Light {
	public Light() {
	}

	public void turnOn() {
		System.out.println("The light is on");
	}

	public void turnOff() {
		System.out.println("The light is off");
	}
}

 

  • The Command for turning on the light – ConcreteCommand #1
public class FlipUpCommand implements Command {
	private Light theLight;

	public FlipUpCommand(Light light) {
		this.theLight = light;
	}

	public void execute() {
		theLight.turnOn();
	}
}

 

  • The Command for turning on the light – ConcreteCommand #2
public class FlipDownCommand implements Command {
	private Light theLight;

	public FlipDownCommand(Light light) {
		this.theLight = light;
	}

	public void execute() {
		theLight.turnOff();
	}
}

 

  • The test class or client
public class PressSwitch {
	public static void main(String[] args) {
		Light lamp = new Light();
		Command switchUp = new FlipUpCommand(lamp);
		Command switchDown = new FlipDownCommand(lamp);
		Switch s = new Switch();
		try {
			if (args[0].equalsIgnoreCase("ON")) {
				s.storeAndExecute(switchUp);
				System.exit(0);
			}
			if (args[0].equalsIgnoreCase("OFF")) {
				s.storeAndExecute(switchDown);
				System.exit(0);
			}
			System.out.println("Argument \"ON\" or \"OFF\" is required.");
		} catch (Exception e) {
			System.out.println("Arguments required.");
		}
	}
}

 

  •  That’s it. Below is list of all design patterns link:

Creational Patterns:

Structural Patterns:

Behavioral Patterns:

Leave a Reply

Your email address will not be published. Required fields are marked *