Command Pattern

Category : Design Patterns | Sub Category : Behavioral Design Patterns | By Prasad Bonam Last updated: 2023-07-09 08:09:37 Viewed : 602


Command Pattern:

One commonly used design pattern for command line applications in Java is the Command pattern. The Command pattern is a behavioral design pattern that decouples the sender of a request from the object that performs the action. It encapsulates a request as an object, thereby allowing clients to parameterize clients with queues, requests, and operations.

Here is an example of how you can implement the Command pattern for a command line application in Java:

java
// Command interface public interface Command { void execute(); } // Concrete command classes public class OpenCommand implements Command { private File file; public OpenCommand(File file) { this.file = file; } @Override public void execute() { // Logic to open the file System.out.println("Opening file: " + file.getName()); } } public class SaveCommand implements Command { private File file; public SaveCommand(File file) { this.file = file; } @Override public void execute() { // Logic to save the file System.out.println("Saving file: " + file.getName()); } } // Invoker class public class CommandInvoker { private Command command; public void setCommand(Command command) { this.command = command; } public void executeCommand() { command.execute(); } } // Client code public class Main { public static void main(String[] args) { // Create the invoker CommandInvoker invoker = new CommandInvoker(); // Create the commands File file = new File("example.txt"); Command openCommand = new OpenCommand(file); Command saveCommand = new SaveCommand(file); // Set and execute the open command invoker.setCommand(openCommand); invoker.executeCommand(); // Set and execute the save command invoker.setCommand(saveCommand); invoker.executeCommand(); } }

In this example, the Command interface represents the commands that can be executed. The OpenCommand and SaveCommand are concrete implementations of the Command interface that perform the open and save operations, respectively. The CommandInvoker class is responsible for setting and executing the commands.

In the Main class, you can create an instance of the CommandInvoker and different command objects (OpenCommand and SaveCommand). You can then set the desired command and execute it using the invoker. This way, the client code is decoupled from the specific command implementation, allowing for easy extensibility and flexibility in adding new commands.

Search
Related Articles

Leave a Comment: