Skip to content
APPCITORThe Tech Blog
Esc

Behavioral – Command Design Pattern

August 7, 2020 1 min read

Behavioral – Command Design Pattern

There are 10 behavioral design patterns and command pattern is one of them. This is used to implement loose coupling in a request-response model. Given below is the process of command pattern.

—-request—-> Invoker —-request—> Command object —-request—>Receiver

The command object is encapsulated. The client program creates the receiver object after passing the request to the receiver and then attach it to the command. After that it creates the invoker object and attach to the command object to perform an action.

Let’s see an example of java program to understand the command pattern.

Assume that your problem is on a remote controller. Remote controller is the client and lamp and stereo are the receivers.

First I created an interface called “Command” for the command that gives for the objects. It is the method “execute()”.

Here is the first receiver “Lamp” class and there are two methods called “on()” and “off()”. Let’s see its corresponding command classes.

Both constructors of the command classes are passed the lamp it is going to control.

“Stereo” also a receiver class same as the “Lamp” class. And both “StereoOffCommand” and “StereoOnDVDCommand” classes are corresponding command classes. Let’s see the program for remote controller.

In “RemoteControl” class you can see by the method “setCommand()” the command is set to execute by the remote after the button is pressed.

You can call all those command objects and by calling the methods you can change the commands dynamically. Output is given below.

You can visit the below given articles to learn about creational design patterns and Structural Design Patterns.

Thank you.

Creational Design Patterns

Singleton Design Pattern

Factory Design Pattern

Abstract Factory Design Pattern

Prototype Design Pattern

Builder Design Pattern

Structural Design Patterns

Facade Design Pattern

Decorator Design Pattern

Adapter Design Pattern

Bridge Design Pattern

Composite Design Pattern

Proxy Design Pattern

Flyweight Design Pattern

Share this article

Keep reading