Command Design Pattern in Java

By | July 6, 2020

In this post, We will talk and learn about the Command Design Pattern in Java

Key Points About Command Design Pattern :

  • Command pattern is a data-driven design pattern and falls under behavioral patterns.
  • In this Design Pattern, a request is wrapped under an object as command and passed to an invoker object. Here the invoker object looks for the appropriate object which can handle this command Object and passes the command object to the corresponding object which executes the command.

Command Design Pattern in JDK:

Now Let’s move towards the implementation of the Command Design Pattern.

Here Below Use Case implementation is done for Command Patten:

We have an interface is called Order which is acting as a command. We have created a class is called Stock class which acts as a request. We have two concrete command classes BuyStock and SellStock implementing Order interface which will be doing actual command processing. A class is called a Broker is created which acts as an invoker object. It can take and place orders.

Here Broker object uses command pattern to identify which object will execute which command based on the type of command. Finally, We have class is called ClientTest, our demo class will use Broker class to demonstrate command pattern.

Below is the complete source code:

Command Design Pattern

StockBroker.java

 

Order.java

 

BuyOrder.java

 

SellOrder.java

 

Stock.java

 

ClientTest.java

Output of client Program:

Stock Name:Google Share and Quantity: 20 bought
Stock Name: Google Share, and Quantity: 20 sold

You May Also Like:

Singleton Design Pattern in java
Prototype Pattern in Java
Factory Pattern in Java
Abstract Factory Pattern in Java
Builder Pattern in Java
Adapter Design Pattern in Java
Decorator Design Pattern in Java
Facade Design Pattern in Java
Bridge Design Pattern in Java.
Observer Design Pattern in Java

That’s all about the Command Design Pattern in Java.
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *