Command Design Pattern

Authors: Chetan Giridhar and Rahul Verma

As per wikipedia:

“In object-oriented programming, the command pattern is a design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time. This information includes the method name, the object that owns the method and values for the method parameters.

Command pattern is one of the design patterns that are categorized under ‘Observer’ design pattern. In command pattern the object is encapsulated in the form of a command, i.e., the object contains all the information that is useful to invoke a method anytime user needs. To give an example, let say we have a user interface where in the background of the interface would turn into RED if the button on the user interface named ‘RED” is clicked. Now the user is unaware what classes or methods the interface would call to make the background turn RED, but the command user sends (by clicking on ‘RED’ button) would ensure the background is turned RED. Thus command pattern gives the client (or the user) to use the interface without the information of the actual actions being performed, without affecting the client program.

The key to implementing this pattern is that the Invoker object should be kept away from specifics of what exactly happens when its methods are executed. This way, the same Invoker object can be used to send commands to objects with similar interfaces.

Command Pattern is associated with three components, the client, the invoker, and the receiver. Let’s take a look at all the three components.

  • Client: the Client represents the one that instantiates the encapsulated object.
  • Invoker: the invoker is responsible for deciding when the method is to be invoked or called.
  • Receiver: the receiver is that part of the code that contains the instructions to execute when a corresponding command is given.

Read More…


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s