Java Command Design Pattern Example
1. Introduction to Java Command Design Pattern
In this post, we will discuss the concept java Command design pattern. The command design pattern is one of the behavioral design pattern in object oriented programming where the object is used to hide the information that is necessary to carry out an action or to activate events later. This data involves the name of the method, the object acquiring the method and values for the parameters of the method.
In java programming, the design patterns not only speed up an object-based application design phase, but also boost the development team productivity and application quality. So, as we know the Command design pattern is a behavioral design pattern that enables us to fully disconnect the sender from the recipient.
When working with this design pattern, Command, recipient, invoker and client are four terms always related to the command pattern. An object of command understands the recipient and invites the recipient method. The command object saves the values for recipient method parameters. The recipient object to implement such methods is indeed processed by aggregation in the command object. When execute() method in command is called, the recipient will then perform this task. An invoking object understands how to run a command and makes invoicing about the execution of the command. The invoker knows nothing about a specific command, only the command interface is known. Invoker objects, command objects and recipient objects shall be maintained by the client object, which receptor objects shall be assigned and which commands shall be assigned to the invoker. Which commands to execute at which points is decided by the client. The command object is carried on to the invoker object in order to execute a command.
This article starts with an answer of different design patterns available, which we comprehend by a real-world scenario of Command design pattern. It would make you grasp exactly when you should use the java Command design pattern. Once we recognize this, we will know precisely how to program the classes to implement the Command design pattern.
2. Types of Java Design Patterns
Design Pattern : Proven solutions to a particular problem are design patterns. A pattern is not a framework and can not be deployed directly through code. For certain issues the design patterns provide developers a common language. Let’s say, the other developer should know exactly what it means if a developer tells another developer that he uses a design pattern. Design patterns are characterised into three different design patterns which are discussed below.
- Creational patterns
- Structural patterns
- Behavioral patterns
2.1 Creational Pattern
Creational design patterns in software engineering are design patterns which address the creative mechanisms of objects and try to create objects suited to the situation. The fundamental form of creation of objects would lead to design challenges or add complexity to design. Creational design patterns address this problem by regulating the creation of this object. Creational design patterns consist of two important ideas. First, encompassing the knowledge and understanding that the system used in the specific classes. Another one is, concerns the creation and combination of instances of such particular classes.
2.2 Structural Pattern
Structural design pattern features seven different types of design patterns. Structural design patterns automate design through an perception of good relations between objects. These design patterns mainly concentrate on connecting classes and objects to create larger structures. The structural design patterns simplify or make the structure easier by establishing the relationship between the structural elements.
2.3 Behavioural Pattern
These design patterns actually concern the communication between classes and objects. Behavioral design patterns are the patterns that most particularly affect communication between objects. This model features eleven different classifications of patterns for interactions between objects. These design patterns are used to deal with algorithms, relations and responsibilities of objects.
In this article, we will expalin the command design pattern by understanding a real world example and then we will implement this pattern using java programming.In Command design pattern it is easier to construct general components with command objects that require delegating, sequencing or executing method calls at the moment you select, without knowing the method class or method parameters. The use of an invoker object allows command executions to be booked conveniently and different methods for commands managed by the invoker object to be implemented without the client having to be conscious of bookkept or modes.
3. Command Design Pattern – Real world example
To simply understand the command design pattern here we are going to take a real life example of Restaurant. Let us suppose, we decided to go to the Restaurant for the lunch with our friends or colleagues. After reaching to the Restaurant we place some order of food. Below image explains the process of order taken from the customer and passes to the cook for cooking.
In the Restaurant there is a Waiter to take orders from the customer. For example, we went to the Restaurant for the lunch and a waiter takes order from us and then the waiter places that order. After placing the order the waiter passes or tells the cook to prepare the food for the customer. Whenever the cook finishes the cooking he passes the cooked food to the waiter and then the waiter serves the cooked food to the customer. Here in this real world example the Cook is represented as a Receiver object, the Customer is represented as a Client object, the Customer order is acting as a Command object and Waiter is represented as a Invoker object. Type of food to be cooked by the cook depends on the order form the customer or client. This may be the good real world example to understand the Command design pattern.
4. Implementing Command Design Pattern
So, now we have understood the concept and real world example of Command design pattern. In this section we will implement the Command design pattern in java program and understand how classes are created based on the Command design pattern. Here we take an example of opening, editing, saving and closing of a text editor.
SublimeText.java
public class SublimeText { public void open() { System.out.println("Sublime Text is Opened"); } public void edit() { System.out.println("Sublime Text is Edited"); } public void save() { System.out.println("Sublime Text is Saved"); } public void close() { System.out.println("Sublime Text is Closed"); } }
In the above code, we have created a class called Sublime Text in which we have created four public methods such as open(), edit(), save() and close(). Inside these function we printed statements such “Sublime Text is Opened”, “Sublime Text is Edited” etc.
Command.java
public interface Command { public void execute(); }
In the above code, we have created an interface known as Command in which we have defined a public method called execute().
OpenSublimeText.java
public class OpenSublimeText implements Command { private SublimeText sublimeText; public OpenSublimeText( SublimeText sublimeText ) { this.sublimeText = sublimeText; } @Override public void execute() { sublimeText.open(); } }
In the above code, we have created a OpenSublimeText class which implements Command interface. In this class we declared a private variable sublimeText which belongs to SublimeText class. We implemented a OpenSublimeText() method with one parameter. Also we have implemented the execute() method which we defined in the command interface and called open() inside this method.
EditSublimeText.java
public class EditSublimeText implements Command { private SublimeText sublimeText; public EditSublimeText( SublimeText sublimeText ) { this.sublimeText = sublimeText; } @Override public void execute() { sublimeText.edit(); } }
In the above code, we have created a EditSublimeText class which implements Command interface. In this class we declared a private variable sublimeText which belongs to SublimeText class. We implemented a EditSublimeText() method with one parameter. Also we have implemented the execute() method which we defined in the command interface and called edit() inside this method.
SaveSublimeText.java
public class SaveSublimeText implements Command { private SublimeText sublimeText; public SaveSublimeText( SublimeText sublimeText ) { this.sublimeText = sublimeText; } @Override public void execute() { sublimeText.save(); } }
In the above code, we have created a SaveSublimeText class which implements Command interface. In this class we declared a private variable sublimeText which belongs to SublimeText class. We implemented a SaveSublimeText() method with one parameter. Also we have implemented the execute() method which we defined in the command interface and called save() inside this method.
CloseSublimeText.java
public class CloseSublimeText implements Command { private SublimeText sublimeText; public CloseSublimeText( SublimeText sublimeText ) { this.sublimeText = sublimeText; } @Override public void execute() { sublimeText.close(); } }
In the above code, we have created a CloseSublimeText class which implements Command interface. In this class we declared a private variable sublimeText which belongs to SublimeText class. We implemented a CloseSublimeText() method with one parameter. Also we have implemented the execute() method which we defined in the command interface and called close() inside this method.
Options.java
public class Options { private Command openSublimeText; private Command editSublimeText; private Command saveSublimeText; private Command closeSublimeText; public Options( Command open, Command edit, Command save, Command close ) { this.openSublimeText = open; this.editSublimeText = edit; this.saveSublimeText = save; this.closeSublimeText = close; } public void pressOpen() { openSublimeText.execute(); } public void pressEdit() { editSublimeText.execute(); } public void pressSave() { saveSublimeText.execute(); } public void pressClose() { closeSublimeText.execute(); } }
In the above code, we have created a Options class in which we have created four Command class object such as openSublimeText, editSublimeText, saveSublimeText and closeSublimeText. Then we created a Options() method with four parameters. And we have implemented four methods such as pressOpen(), pressEdit(), pressSave() and pressClose() in which we called execute() method using Command objects.
CommandDesignPattern.java
public class CommandDesignPattern { public static void main( String[] args ) { SublimeText sublimeText = new SublimeText(); Command openSublimeText = new OpenSublimeText(sublimeText); Command editSublimeText = new EditSublimeText(sublimeText); Command saveSublimeText = new SaveSublimeText(sublimeText); Command closeSublimeText = new CloseSublimeText(sublimeText); Options option = new Options(openSublimeText,editSublimeText, saveSublimeText,closeSublimeText); option.pressOpen(); option.pressEdit(); option.pressSave(); option.pressClose(); } }
In the above code we created a CommandDesignPattern class in which we implemted the main() method. In the main() method we created a SublimeText class object and four Command class objects openSublimeText, editSublimeText, saveSublimeText and closeSublimeText. Then we created a Options class object which consists of four Command class object. Using the Options class objects we called the four methods such as pressOpen(), pressEdit(), pressSave() and pressClose().
Sublime Text is Opened Sublime Text is Edited Sublime Text is Saved Sublime Text is Closed
From the output we understand when the open command is executed the sublime text will be opened and when the edit command is executed the sublime text is edited and when the save command is executed the sublime text is saved and finally when the close command is fired the sublime text is closed. Command design patterns that can assist you to write adaptable, loosely linked code in your application for actions and events. The command design pattern is used in simple words to separate an activity request from the object that conducts the action in effect.
5. Benefits of Command Design Pattern
Here, in this section we will talk about some of the command design pattern’s advantages. These following are the advantages:
- Using command design pattern we can create a series of commands with a queue system.
- Another important benefit of this design pattern is a rollback system with the Command pattern can also be set.
- Extensions to add a new command is easy and can be done without changing the existing code.
- Command design pattern has ability to undo or redo easily in the syatem.
- Command design pattern disassembles the classes which call on the object, which knows how to perform it.
- In this design pattern a set of simple commands can be assembled into a complex one.
- In command design pattern without breaking existing client code, you can add new commands to the app.
6. Conclusion
It is concluded that we should therefore follow a Command Design pattern if we’ve got several commands to execute and it doesn’t matter whether or not those commands are related. The Command design pattern aims to hide commands as objects, allowing different recipients, depending on the design of the recipient. When we implement “undo,” you can use Command and Memento together. This means that commands perform different operations over a target object, whereas memento save the status of that object before a command is executed.
7. Download the Project
You can download the project files for the above example from the below link:
You can download the full source code of this example here: Java Command Design Pattern