What is command design pattern explain with a java example
- User
What is command design pattern explain with a java example
- Assistant
The Command design pattern is a behavioral design pattern that turns a request into a stand-alone object that contains all information about the request. This transformation lets you pass requests as method arguments, delay or queue a request's execution, and support undoable operations.
In the Command design pattern, a class represents a request by having a method for executing the request. The actual request is carried out by an object that implements a particular interface. The interface typically has a single method that carries out the request.
Here is an example of the Command design pattern in Java:
First, we define the interface for the command:
codepublic interface Command { void execute(); }Next, we define a concrete implementation of the command:
codepublic class ConcreteCommand implements Command { private Receiver receiver; public ConcreteCommand(Receiver receiver) { this.receiver = receiver; } @Override public void execute() { receiver.action(); } }The Receiver class represents the object that the command will operate on:
codepublic class Receiver { public void action() { // Perform the action } }Finally, we have the Invoker class, which holds a command and invokes it:
codepublic class Invoker { private Command command; public void setCommand(Command command) { this.command = command; } public void invoke() { command.execute(); } }To use the Command design pattern, we create a ConcreteCommand object and set it as the command for an Invoker object. When we invoke the command, it will execute the request by calling the action method on the Receiver object.
Here's an example of using the Command design pattern:
codeReceiver receiver = new Receiver(); Command command = new ConcreteCommand(receiver); Invoker invoker = new Invoker(); invoker.setCommand(command); invoker.invoke();This will execute the action method on the Receiver object.
- User
Give a real life example of this design pattern with code in java
- Assistant
One real-life example of the Command design pattern is a simple remote control with a single button. The button can be pressed to turn a device on or off.
We can implement this example in Java as follows:
First, we define the interface for the command:
codepublic interface Command { void execute(); }Next, we define the concrete command for turning the device on:
code - User
Give yet another example
- Assistant
Here is another example of the Command design pattern in Java. This example demonstrates a simple text editor with the ability to undo and redo text operations.
- User
give a modified version of 1st example by invoking 2 devices say a television and a radio, include commands to turn on all at once and turn off all at once
- Assistant