SlideShare a Scribd company logo
1 of 6
Download to read offline
Command pattern in Java
The Command pattern is known as a behavioral pattern, as it's used to manage
algorithms, relationships and responsibilities between objects. The Command
pattern transforms a set of related algorithms into a type, instances of which
encapsulate all the logic and data required to perform a particular algorithm.
Purpose of Command pattern
Design patterns not only accelerate the design phase of an object-oriented (OO) project
but also increase the productivity of the development team and quality of the software.
A Command pattern is an object behavioral pattern that allows us to achieve complete
decoupling between the sender and the receiver.
A sender is an object that invokes an operation, and a receiver is an object that receives
the request to execute a certain operation. With decoupling, the sender has no knowledge
of the Receiver's interface.
The term request here refers to the command that is to be executed. The Command
pattern also allows us to vary when and how a request is fulfilled. Therefore, a Command
pattern provides us flexibility as well as extensibility.
Scope of Command pattern
The most common use of the Command pattern is to execute, undo and redo actions. But
commands can be asked to perform other tasks as well.
Using the Command pattern, the Invoker that issues a request on behalf of the client and
the set of service-rendering Receiver objects can be decoupled.
The Command pattern suggests creating an abstraction for the processing to be carried
out or the action to be taken in response to client requests.
This abstraction can be designed to declare a common interface to be implemented by
different concrete implementers referred to as Command objects.
Each Command object represents a different type of client request and the corresponding
processing.
A given Command object is responsible for offering the functionality required to process
the request it represents, but it does not contain the actual implementation of the
functionality.
Intent of Command pattern
o encapsulate a request in an object .
o allows the parameterization of clients with different requests.
o allows saving the requests in a queue.
o An object-oriented callback.
Name and Classification
Design patterns not only accelerate the design phase of an object-oriented project but also
increase the productivity of the development team and quality of the software. A
Command pattern is an object behavioral pattern that allows us to achieve complete
decoupling between the sender and the receiver. A sender is an object that invokes an
operation, and a receiver is an object that receives the request to execute a certain
operation. With decoupling, the sender has no knowledge of the Receiver's inter.
Problem and Solution for Command pattern
The Command Pattern is useful when:
 A history of requests is needed .
 We need callback functionality.
 Requests need to be handled at variant times or in variant orders.
 The invoker should be decoupled from the object handling the invocation.
 Coupling the invoker of a request to a particular request should be avoided.
 It should be possible to configure an object with a request.
Consequences
Pros:
 decouples the object that invokes the operation from the one that know how
to perform it.
 This pattern helps in terms of extensible as we can add a new command
without changing the existing code.
 It allows you to create a sequence of commands named macro. To run the
macro, create a list of Command instances and call the execute method of
all commands.
 Ability to undo/redo easily.
Cons:
 increase in the number of classes for each individual command.
 There are a high number of classes and objects working together to achieve a goal.
Structure
Fig: Object Behavioral Command pattern
Command declares an interface for all commands, providing a simple execute() method
which asks the Receiver of the command to carry out an operation. The Receiver has the
knowledge of what to do to carry out the request. The Invoker holds a command and can
get the Command to execute a request by calling the execute method. The Client creates
ConcreteCommands and sets a Receiver for the command. The ConcreteCommand
defines a binding between the action and the receiver. When the Invoker calls execute the
ConcreteCommand will run one or more actions on the Receiver.
The following sequence diagram shows the relationship in a clearer way:
Command Pattern: participants
Command:– Declares an interface for executing an operation.
ConcreteCommand :– Implements execute( ) by invoking the corresponding operation(s)
on Receiver(s).
Client:– Creates a ConcreteCommand object and sets its Receiver.
Invoker: – Asks its Command to carry out the request.
Receiver:– Any classes that know how to perform the operation(s) associated with
carrying out a request.
Collaborations
 The client creates a ConcreteCommand object and specifies its receiver.
 An Invoker object stores the ConcreteCommand object.
 The invoker issues a request by calling Execute on the command. When
commands are undoable, ConcreteCommand stores state for undoing the
command prior to invoking Execute.
 The ConcreteCommand object invokes operations on its receiver to carry out the
request
Command pattern example code
Let's use a switch control as the example. Our switch is the center of home automation
and can control everything. We'll just use a light as an example, that we can switch on or
off, but we could add many more commands:
o First we'll create our command interface:
//Command
public interface Command{
public void execute();
}
o Now let's create two concrete commands. One will turn on the lights, another
turns off lights:
//Concrete Command
public class LightOnCommand implements Command{
//reference to the light
Light light;
public LightOnCommand(Light light){
this.light = light;
}
public void execute(){
light.switchOn();
}
}
//Concrete Command
public class LightOffCommand implements Command{
//reference to the light
Light light;
public LightOffCommand(Light light){
this.light = light;
}
public void execute(){
light.switchOff();
}
}
o Light is our receiver class, so let's set that up now:
//Receiver
public class Light{
private boolean on;
public void switchOn(){
on = true;
}
public void switchOff(){
on = false;
}
}
o Our invoker in this case is the remote control
//Invoker
public class RemoteControl{
private Command command;
public void setCommand(Command command){
this.command = command;
}
public void pressButton(){
command.execute();
}
}
o Finally we'll set up a client to use the invoker
//Client
public class Client{
public static void main(String[] args) {
RemoteControl control = new RemoteControl();
Light light = new Light();
Command lightsOn = new LightsOnCommand(light);
Command lightsOff = new LightsOffCommand(light);
//switch on
control.setCommand(lightsOn);
control.pressButton();
//switch off
control.setCommand(lightsOff);
control.pressButton();
}
}
The Uses of Command Pattern in real System
 Graphic User Interface (GUI): In GUI and menu items, we use command pattern.
By clicking a button we can read the current information of GUI and take an
action.
 Macro Recording: If each of user action is implemented as a separate Command,
we can record all the user actions in a Macro as a series of Commands. We can use
this series to implement the “Playback” feature. In this way, Macro can keep on
doing same set of actions with each replay.
 Multi-step Undo: When each step is recorded as a Command, we can use it to
implement Undo feature in which each step can by undo. It is used in text editors
like MS-Word.
 Networking: We can also send a complete Command over the network to a remote
machine where all the actions encapsulated within a Command are executed.
 Progress Bar: We can implement an installation routine as a series of Commands.
Each Command provides the estimate time. When we execute the installation
routine, with each command we can display the progress bar.
 Transactions: In a transactional behavior code there are multiple tasks/updates.
When all the tasks are done then only transaction is committed. Else we have to
rollback the transaction. In such a scenario each step is implemented as separate
Command.

More Related Content

What's hot

How to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksHow to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksKaty Slemon
 
Chain of Responsibility Pattern
Chain of Responsibility PatternChain of Responsibility Pattern
Chain of Responsibility PatternHüseyin Ergin
 
Model View Command Pattern
Model View Command PatternModel View Command Pattern
Model View Command PatternAkash Kava
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsCarol McDonald
 
MCE^3 - Gregory Kick - Dagger 2
MCE^3 - Gregory Kick - Dagger 2 MCE^3 - Gregory Kick - Dagger 2
MCE^3 - Gregory Kick - Dagger 2 PROIDEA
 
Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptxtalha ijaz
 
Android development training programme , Day 3
Android development training programme , Day 3Android development training programme , Day 3
Android development training programme , Day 3DHIRAJ PRAVIN
 
Memento Pattern Implementation
Memento Pattern ImplementationMemento Pattern Implementation
Memento Pattern ImplementationSteve Widom
 
Concurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksConcurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksWO Community
 
Function & procedure
Function & procedureFunction & procedure
Function & procedureatishupadhyay
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsleminhvuong
 

What's hot (20)

How to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksHow to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooks
 
Tech talk
Tech talkTech talk
Tech talk
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java components in Mule
Java components in MuleJava components in Mule
Java components in Mule
 
Types of MessageRouting in Mule
Types of MessageRouting in MuleTypes of MessageRouting in Mule
Types of MessageRouting in Mule
 
Chain of Responsibility Pattern
Chain of Responsibility PatternChain of Responsibility Pattern
Chain of Responsibility Pattern
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
 
Model View Command Pattern
Model View Command PatternModel View Command Pattern
Model View Command Pattern
 
CQRS and Event Sourcing
CQRS and Event SourcingCQRS and Event Sourcing
CQRS and Event Sourcing
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Android session-5-sajib
Android session-5-sajibAndroid session-5-sajib
Android session-5-sajib
 
MCE^3 - Gregory Kick - Dagger 2
MCE^3 - Gregory Kick - Dagger 2 MCE^3 - Gregory Kick - Dagger 2
MCE^3 - Gregory Kick - Dagger 2
 
Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptx
 
Call Back
Call BackCall Back
Call Back
 
Android development training programme , Day 3
Android development training programme , Day 3Android development training programme , Day 3
Android development training programme , Day 3
 
Memento Pattern Implementation
Memento Pattern ImplementationMemento Pattern Implementation
Memento Pattern Implementation
 
Concurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksConcurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background Tasks
 
Function & procedure
Function & procedureFunction & procedure
Function & procedure
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 

Similar to Command pattern in Java

How do i implement command design pattern in the java programming course with...
How do i implement command design pattern in the java programming course with...How do i implement command design pattern in the java programming course with...
How do i implement command design pattern in the java programming course with...kritikumar16
 
How do i implement command design pattern in the java programming course with...
How do i implement command design pattern in the java programming course with...How do i implement command design pattern in the java programming course with...
How do i implement command design pattern in the java programming course with...kritikumar16
 
Command pattern vs. MVC: Lean Beans (are made of this)
Command pattern vs. MVC: Lean Beans (are made of this)Command pattern vs. MVC: Lean Beans (are made of this)
Command pattern vs. MVC: Lean Beans (are made of this)philipdurbin
 
Behavioral pattern 4
Behavioral pattern 4Behavioral pattern 4
Behavioral pattern 4Naga Muruga
 
Angular 16 – the rise of Signals
Angular 16 – the rise of SignalsAngular 16 – the rise of Signals
Angular 16 – the rise of SignalsCoding Academy
 
Effective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsSrikanth Shenoy
 
Guidelines to understand durable functions with .net core, c# and stateful se...
Guidelines to understand durable functions with .net core, c# and stateful se...Guidelines to understand durable functions with .net core, c# and stateful se...
Guidelines to understand durable functions with .net core, c# and stateful se...Concetto Labs
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
 
Nt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNicole Gomez
 
Remote Method Invocation (Java RMI)
Remote Method Invocation (Java RMI)Remote Method Invocation (Java RMI)
Remote Method Invocation (Java RMI)Sonali Parab
 
Meetup - Getting Started with MVVM Light for WPF - 11 may 2019
Meetup  - Getting Started with MVVM Light for WPF - 11 may 2019Meetup  - Getting Started with MVVM Light for WPF - 11 may 2019
Meetup - Getting Started with MVVM Light for WPF - 11 may 2019iFour Technolab Pvt. Ltd.
 
MarGotAspect - An AspectC++ code generator for the mARGOt framework
MarGotAspect - An AspectC++ code generator for the mARGOt frameworkMarGotAspect - An AspectC++ code generator for the mARGOt framework
MarGotAspect - An AspectC++ code generator for the mARGOt frameworkLeonardo Arcari
 
Lesson10 behavioral patterns
Lesson10 behavioral patternsLesson10 behavioral patterns
Lesson10 behavioral patternsOktJona
 
Javascripts hidden treasures BY - https://geekyants.com/
Javascripts hidden treasures            BY  -  https://geekyants.com/Javascripts hidden treasures            BY  -  https://geekyants.com/
Javascripts hidden treasures BY - https://geekyants.com/Geekyants
 
Vert.x for Microservices Architecture
Vert.x for Microservices ArchitectureVert.x for Microservices Architecture
Vert.x for Microservices ArchitectureIdan Fridman
 
iOS Architectures
iOS ArchitecturesiOS Architectures
iOS ArchitecturesHung Hoang
 
iOS app dev Training - Session1
iOS app dev Training - Session1iOS app dev Training - Session1
iOS app dev Training - Session1Hussain Behestee
 

Similar to Command pattern in Java (20)

How do i implement command design pattern in the java programming course with...
How do i implement command design pattern in the java programming course with...How do i implement command design pattern in the java programming course with...
How do i implement command design pattern in the java programming course with...
 
How do i implement command design pattern in the java programming course with...
How do i implement command design pattern in the java programming course with...How do i implement command design pattern in the java programming course with...
How do i implement command design pattern in the java programming course with...
 
Command pattern vs. MVC: Lean Beans (are made of this)
Command pattern vs. MVC: Lean Beans (are made of this)Command pattern vs. MVC: Lean Beans (are made of this)
Command pattern vs. MVC: Lean Beans (are made of this)
 
Behavioral pattern 4
Behavioral pattern 4Behavioral pattern 4
Behavioral pattern 4
 
Angular 16 – the rise of Signals
Angular 16 – the rise of SignalsAngular 16 – the rise of Signals
Angular 16 – the rise of Signals
 
Effective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjects
 
Guidelines to understand durable functions with .net core, c# and stateful se...
Guidelines to understand durable functions with .net core, c# and stateful se...Guidelines to understand durable functions with .net core, c# and stateful se...
Guidelines to understand durable functions with .net core, c# and stateful se...
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
 
Angularjs
AngularjsAngularjs
Angularjs
 
Nt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language Analysis
 
Remote Method Invocation (Java RMI)
Remote Method Invocation (Java RMI)Remote Method Invocation (Java RMI)
Remote Method Invocation (Java RMI)
 
Meetup - Getting Started with MVVM Light for WPF - 11 may 2019
Meetup  - Getting Started with MVVM Light for WPF - 11 may 2019Meetup  - Getting Started with MVVM Light for WPF - 11 may 2019
Meetup - Getting Started with MVVM Light for WPF - 11 may 2019
 
MarGotAspect - An AspectC++ code generator for the mARGOt framework
MarGotAspect - An AspectC++ code generator for the mARGOt frameworkMarGotAspect - An AspectC++ code generator for the mARGOt framework
MarGotAspect - An AspectC++ code generator for the mARGOt framework
 
Lesson10 behavioral patterns
Lesson10 behavioral patternsLesson10 behavioral patterns
Lesson10 behavioral patterns
 
Javascripts hidden treasures BY - https://geekyants.com/
Javascripts hidden treasures            BY  -  https://geekyants.com/Javascripts hidden treasures            BY  -  https://geekyants.com/
Javascripts hidden treasures BY - https://geekyants.com/
 
Basic java
Basic java Basic java
Basic java
 
Vert.x for Microservices Architecture
Vert.x for Microservices ArchitectureVert.x for Microservices Architecture
Vert.x for Microservices Architecture
 
RMI (Remote Method Invocation)
RMI (Remote Method Invocation)RMI (Remote Method Invocation)
RMI (Remote Method Invocation)
 
iOS Architectures
iOS ArchitecturesiOS Architectures
iOS Architectures
 
iOS app dev Training - Session1
iOS app dev Training - Session1iOS app dev Training - Session1
iOS app dev Training - Session1
 

Recently uploaded

Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Jack DiGiovanna
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptxAnupama Kate
 
Data Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptxData Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptxFurkanTasci3
 
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...Florian Roscheck
 
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改atducpo
 
Call Girls In Mahipalpur O9654467111 Escorts Service
Call Girls In Mahipalpur O9654467111  Escorts ServiceCall Girls In Mahipalpur O9654467111  Escorts Service
Call Girls In Mahipalpur O9654467111 Escorts ServiceSapana Sha
 
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls DubaiDubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls Dubaihf8803863
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...Suhani Kapoor
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Call Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts Service
Call Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts ServiceCall Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts Service
Call Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts Servicejennyeacort
 
20240419 - Measurecamp Amsterdam - SAM.pdf
20240419 - Measurecamp Amsterdam - SAM.pdf20240419 - Measurecamp Amsterdam - SAM.pdf
20240419 - Measurecamp Amsterdam - SAM.pdfHuman37
 
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Spark3's new memory model/management
Spark3's new memory model/managementSpark3's new memory model/management
Spark3's new memory model/managementakshesh doshi
 
{Pooja: 9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
{Pooja:  9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...{Pooja:  9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
{Pooja: 9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...Pooja Nehwal
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfSocial Samosa
 
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptdokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptSonatrach
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfLars Albertsson
 
Customer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptxCustomer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptxEmmanuel Dauda
 
Unveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystUnveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystSamantha Rae Coolbeth
 

Recently uploaded (20)

Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx
 
Data Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptxData Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptx
 
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
 
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
 
Call Girls In Mahipalpur O9654467111 Escorts Service
Call Girls In Mahipalpur O9654467111  Escorts ServiceCall Girls In Mahipalpur O9654467111  Escorts Service
Call Girls In Mahipalpur O9654467111 Escorts Service
 
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls DubaiDubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
 
Call Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts Service
Call Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts ServiceCall Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts Service
Call Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts Service
 
20240419 - Measurecamp Amsterdam - SAM.pdf
20240419 - Measurecamp Amsterdam - SAM.pdf20240419 - Measurecamp Amsterdam - SAM.pdf
20240419 - Measurecamp Amsterdam - SAM.pdf
 
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
 
Spark3's new memory model/management
Spark3's new memory model/managementSpark3's new memory model/management
Spark3's new memory model/management
 
{Pooja: 9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
{Pooja:  9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...{Pooja:  9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
{Pooja: 9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
 
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptdokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdf
 
Customer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptxCustomer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptx
 
Unveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystUnveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data Analyst
 

Command pattern in Java

  • 1. Command pattern in Java The Command pattern is known as a behavioral pattern, as it's used to manage algorithms, relationships and responsibilities between objects. The Command pattern transforms a set of related algorithms into a type, instances of which encapsulate all the logic and data required to perform a particular algorithm. Purpose of Command pattern Design patterns not only accelerate the design phase of an object-oriented (OO) project but also increase the productivity of the development team and quality of the software. A Command pattern is an object behavioral pattern that allows us to achieve complete decoupling between the sender and the receiver. A sender is an object that invokes an operation, and a receiver is an object that receives the request to execute a certain operation. With decoupling, the sender has no knowledge of the Receiver's interface. The term request here refers to the command that is to be executed. The Command pattern also allows us to vary when and how a request is fulfilled. Therefore, a Command pattern provides us flexibility as well as extensibility. Scope of Command pattern The most common use of the Command pattern is to execute, undo and redo actions. But commands can be asked to perform other tasks as well. Using the Command pattern, the Invoker that issues a request on behalf of the client and the set of service-rendering Receiver objects can be decoupled. The Command pattern suggests creating an abstraction for the processing to be carried out or the action to be taken in response to client requests. This abstraction can be designed to declare a common interface to be implemented by different concrete implementers referred to as Command objects. Each Command object represents a different type of client request and the corresponding processing. A given Command object is responsible for offering the functionality required to process the request it represents, but it does not contain the actual implementation of the functionality.
  • 2. Intent of Command pattern o encapsulate a request in an object . o allows the parameterization of clients with different requests. o allows saving the requests in a queue. o An object-oriented callback. Name and Classification Design patterns not only accelerate the design phase of an object-oriented project but also increase the productivity of the development team and quality of the software. A Command pattern is an object behavioral pattern that allows us to achieve complete decoupling between the sender and the receiver. A sender is an object that invokes an operation, and a receiver is an object that receives the request to execute a certain operation. With decoupling, the sender has no knowledge of the Receiver's inter. Problem and Solution for Command pattern The Command Pattern is useful when:  A history of requests is needed .  We need callback functionality.  Requests need to be handled at variant times or in variant orders.  The invoker should be decoupled from the object handling the invocation.  Coupling the invoker of a request to a particular request should be avoided.  It should be possible to configure an object with a request. Consequences Pros:  decouples the object that invokes the operation from the one that know how to perform it.  This pattern helps in terms of extensible as we can add a new command without changing the existing code.  It allows you to create a sequence of commands named macro. To run the macro, create a list of Command instances and call the execute method of all commands.  Ability to undo/redo easily. Cons:  increase in the number of classes for each individual command.  There are a high number of classes and objects working together to achieve a goal.
  • 3. Structure Fig: Object Behavioral Command pattern Command declares an interface for all commands, providing a simple execute() method which asks the Receiver of the command to carry out an operation. The Receiver has the knowledge of what to do to carry out the request. The Invoker holds a command and can get the Command to execute a request by calling the execute method. The Client creates ConcreteCommands and sets a Receiver for the command. The ConcreteCommand defines a binding between the action and the receiver. When the Invoker calls execute the ConcreteCommand will run one or more actions on the Receiver. The following sequence diagram shows the relationship in a clearer way:
  • 4. Command Pattern: participants Command:– Declares an interface for executing an operation. ConcreteCommand :– Implements execute( ) by invoking the corresponding operation(s) on Receiver(s). Client:– Creates a ConcreteCommand object and sets its Receiver. Invoker: – Asks its Command to carry out the request. Receiver:– Any classes that know how to perform the operation(s) associated with carrying out a request. Collaborations  The client creates a ConcreteCommand object and specifies its receiver.  An Invoker object stores the ConcreteCommand object.  The invoker issues a request by calling Execute on the command. When commands are undoable, ConcreteCommand stores state for undoing the command prior to invoking Execute.  The ConcreteCommand object invokes operations on its receiver to carry out the request Command pattern example code Let's use a switch control as the example. Our switch is the center of home automation and can control everything. We'll just use a light as an example, that we can switch on or off, but we could add many more commands: o First we'll create our command interface: //Command public interface Command{ public void execute(); } o Now let's create two concrete commands. One will turn on the lights, another turns off lights: //Concrete Command public class LightOnCommand implements Command{ //reference to the light Light light; public LightOnCommand(Light light){ this.light = light;
  • 5. } public void execute(){ light.switchOn(); } } //Concrete Command public class LightOffCommand implements Command{ //reference to the light Light light; public LightOffCommand(Light light){ this.light = light; } public void execute(){ light.switchOff(); } } o Light is our receiver class, so let's set that up now: //Receiver public class Light{ private boolean on; public void switchOn(){ on = true; } public void switchOff(){ on = false; } } o Our invoker in this case is the remote control //Invoker public class RemoteControl{ private Command command; public void setCommand(Command command){ this.command = command; } public void pressButton(){ command.execute(); } } o Finally we'll set up a client to use the invoker //Client public class Client{ public static void main(String[] args) { RemoteControl control = new RemoteControl();
  • 6. Light light = new Light(); Command lightsOn = new LightsOnCommand(light); Command lightsOff = new LightsOffCommand(light); //switch on control.setCommand(lightsOn); control.pressButton(); //switch off control.setCommand(lightsOff); control.pressButton(); } } The Uses of Command Pattern in real System  Graphic User Interface (GUI): In GUI and menu items, we use command pattern. By clicking a button we can read the current information of GUI and take an action.  Macro Recording: If each of user action is implemented as a separate Command, we can record all the user actions in a Macro as a series of Commands. We can use this series to implement the “Playback” feature. In this way, Macro can keep on doing same set of actions with each replay.  Multi-step Undo: When each step is recorded as a Command, we can use it to implement Undo feature in which each step can by undo. It is used in text editors like MS-Word.  Networking: We can also send a complete Command over the network to a remote machine where all the actions encapsulated within a Command are executed.  Progress Bar: We can implement an installation routine as a series of Commands. Each Command provides the estimate time. When we execute the installation routine, with each command we can display the progress bar.  Transactions: In a transactional behavior code there are multiple tasks/updates. When all the tasks are done then only transaction is committed. Else we have to rollback the transaction. In such a scenario each step is implemented as separate Command.