Command
from: Command Pattern Tutorial with Java Examples
Example
Command
public interface Command {
public void execute();
}
public class LunchCommand implements Command {
Lunch lunch;
public LunchCommand(Lunch lunch) {
this.lunch = lunch;
}
@Override
public void execute() {
lunch.makeLunch();
}
}
public class DinnerCommand implements Command {
Dinner dinner;
public DinnerCommand(Dinner dinner) {
this.dinner = dinner;
}
@Override
public void execute() {
dinner.makeDinner();
}
}
Receiver
public class Lunch {
public void makeLunch() {
System.out.println("Lunch is being made");
}
}
public class Dinner {
public void makeDinner() {
System.out.println("Dinner is being made");
}
}
Invoker
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();
}
}
Usage
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();
}
}
from: Command Pattern