Welcome to our comprehensive Java tutorial on the Command Pattern! This pattern is a behavioral design pattern that turns a request into a stand-alone object, allowing for the separation of the invoker and receiver. Let's dive in and explore this pattern, starting from the basics and gradually moving towards advanced examples.
The Command Pattern is all about encapsulating a request as an object, enabling the separation of invoking an action from the action itself. This allows for the passing of requests between objects as a way of communication, allowing for easier decoupling and reusability of code. 💡 Pro Tip: This pattern is particularly useful in GUI applications and undo/redo functions.
execute() and undo() methods.Let's create a simple example of the Command Pattern for a coffee shop. We'll have Coffee, Tea, and Cake orders as commands, and a Waiter as the invoker.
interface Order {
void execute();
void undo();
}class Coffee implements Order {
private Waiter waiter;
public Coffee(Waiter waiter) {
this.waiter = waiter;
}
@Override
public void execute() {
System.out.println("Preparing coffee...");
waiter.deliver("Coffee is ready.");
}
@Override
public void undo() {
System.out.println("Removing coffee...");
waiter.undo("Coffee was canceled.");
}
}
// Similar classes for Tea and Cakeclass Waiter {
private Order order;
public void takeOrder(Order order) {
this.order = order;
order.execute();
}
public void undoLastOrder() {
order.undo();
}
public void deliver(String message) {
System.out.println(message);
}
public void undo(String message) {
System.out.println(message);
}
}Now we can create a Client and use the Command Pattern.
public class Main {
public static void main(String[] args) {
Waiter waiter = new Waiter();
Coffee coffee = new Coffee(waiter);
Tea tea = new Tea(waiter);
waiter.takeOrder(coffee);
waiter.takeOrder(tea);
waiter.undoLastOrder();
}
}In this example, the Main class acts as the client, creating orders and giving them to the Waiter. The Waiter then uses these orders to take and deliver orders. If an order needs to be undone, the Waiter can undo the last order.
We've covered the basics of the Command Pattern in Java, and we've seen how it can be used to create a simple coffee shop example. This pattern is a powerful tool for decoupling objects and making your code more modular and reusable.
Which class acts as the invoker in the Command Pattern example?