Command Pattern

Will Curry
2 min readSep 19, 2016

The command pattern is a common design pattern which I have used in my Console Menu Libary for Java. The command pattern encapsulates a request as an object. So to implement the command pattern you would have a command interface and then a command object implementing that interface. There is a client class which calls a method in an invoker class which will then create the command and execute it. When the command is executed it will call the receiver class to do the action. This means the responsiblity of executing a command lies within the command and receiver class. This is useful as it means you decouple the receiver from the invoker. It is also creating an object-oriented callback.

I will do an example of an Order command following this pattern. So we have a customer class who is the client:

public class Customer {
private final FoodShop foodShop;

public Customer(FoodShop foodShop) {
this.foodShop = foodShop;
}
public void wantsFood() {
foodShop.order();
}
}

Then we have the food shop which is the invoker:

public class FoodShop {
public void order() {
Command order = new Order(new Cook());
order.execute();
}
}

And then we have the Order command:

public class Order implements Command {
private final Cook cook;

public Order(Cook cook) {
this.cook = cook;
}

@Override
public void execute() {
System.out.print("What food would you like?");
Scanner scanner = new Scanner(System.in);
cook.cookFood(scanner.nextLine());
}
}

And then the receiver:

public class Cook {
public void cookFood(String food) {
System.out.print(food + " has been cooked!");
}
}

This is a simple implementation of the command pattern.

The commands you create should always have an execute and it should be void. It does not have to be void, but I strongly recommend that it is or you will be putting some of the commands responsibility in the invoker class which you just should not do or your software will be reluctant to change.

--

--