command_pattern
command_pattern
Command pattern is a data driven design pattern and falls under behavioral pattern category. A
request is wrapped under an object as command and passed to invoker object. Invoker object
looks for the appropriate object which can handle this command and passes the command to the
corresponding object which executes the command.
Implementation
We have created an interface Order which is acting as a command. We have created a Stock class
which acts as a request. We have concrete command classes BuyStock and SellStock
implementing Order interface which will do actual command processing. A class Broker is created
which acts as an invoker object. It can take and place orders.
Broker object uses command pattern to identify which object will execute which command based
on the type of command. CommandPatternDemo, our demo class, will use Broker class to
demonstrate command pattern.
Step 1
Create a command interface.
Order.java
Step 2
Create a request class.
Stock.java
public class Stock {
Step 3
Create concrete classes implementing the Order interface.
BuyStock.java
SellStock.java
Step 4
Create command invoker class.
Broker.java
import java.util.ArrayList;
import java.util.List;
Step 5
Use the Broker class to take and execute commands.
CommandPatternDemo.java
broker.placeOrders();
}
}
Step 6
Verify the output.