Mastering Java Design Patterns - Day 12: Command Pattern
Emmanuel Hadjistratis (he/him)
No more security gaps or inefficient APIs | I optimize your backend infrastructure for maximum performance
Welcome to another exciting day in our series on Java Design Patterns! Yesterday, we discussed the Chain of Responsibility Pattern. Today, we'll explore the Command Pattern, a versatile tool for encapsulating all the information needed to perform an action or trigger an event at a later time.
What is the Command Pattern?
The Command Pattern encapsulates a request as an object, allowing you to parameterize clients with different requests, queue or log requests, and support undoable operations. This pattern is highly useful when you need to issue requests to objects without knowing anything about the operation being requested or the receiver of the request.
Why Use the Command Pattern?
How to Implement the Command Pattern in Java
Here's a basic implementation of the Command Pattern:
// Command interface
interface Command {
void execute();
}
// Concrete Commands
class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
public void execute() {
light.turnOn();
}
}
// Concrete Commands
class LightOffCommand implements Command {
private Light light;
public LightOffCommand(Light light) {
this.light = light;
}
public void execute() {
light.turnOff();
}
}
// Receiver
class Light {
public void turnOn() {
System.out.println("The light is on");
}
public void turnOff() {
System.out.println("The light is off");
}
}
// Invoker
class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void pressButton() {
command.execute();
}
}
// Client code
public class CommandPatternDemo {
public static void main(String[] args) {
Light light = new Light();
Command lightsOn = new LightOnCommand(light);
Command lightsOff = new LightOffCommand(light);
RemoteControl control = new RemoteControl();
control.setCommand(lightsOn);
control.pressButton();
control.setCommand(lightsOff);
control.pressButton();
}
}
Discussion:
Have you used the Command Pattern to manage user actions or undo functionalities in your applications? What challenges did you encounter, and how did the pattern help solve them? Share your insights and experiences in the comments below!
?? Call to Action: If you enjoyed this post, don’t forget to like, share, and comment! Follow #ehadjistratis for ongoing discussions on Java Design Patterns and professional development in tech.
Looking forward to your thoughts and examples!
Stay tuned for tomorrow's topic: Interpreter Pattern.
#Java #DesignPatterns #CommandPattern #Programming #Coding #SoftwareDevelopment #LearningJourney #JuniorDevelopers #TechCommunity #ehadjistratis