BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

Design Patterns - Command Pattern

Patterns.png




Bookmark and Share





bogotobogo.com site search:

Command Pattern

Intent
Encapsulates a request as an object, thereby letting us parameterize other objects with different requests, queue or log requests, and support undoable operations.



CommandDiagram

Command Pattern - simple example 1

The Command object has the key of the pattern.


For example, LightOnCommand object has the right method (execute(), and actually, doing light->On()) of the receiver (Light object). This is possible, the command object has the pointer to the Light receiver as its member. So, when asked to perform an action on a receiver, we just feeding the command object to the invoker.

The invoker which is named as control in the code make a request of a Command object by calling that object's execute() method. Then, since the method knows what the receiver is, it invokes the action on that receiver.

Here is an example code:

#include <iostream>
 
using namespace std;

// Command Interface
class Command
{
public:
	virtual void execute() = 0;
};
 
// Receiver Class
class Light 
{
public:
	void on() {
		cout << "The light is on\n";
	}
	void off() {
		cout << "The light is off\n";
	}
}; 

// Command for turning on the light
class LightOnCommand : public Command 
{
public:
        LightOnCommand(Light *light) : mLight(light) {}
	void execute(){
		mLight->on();
	}
private:
	Light *mLight;
};
 
// Command for turning off the light
class LightOffCommand : public Command 
{
public:
        LightOffCommand(Light *light) : mLight(light) {}
	void execute(){
		mLight->off();
	}
private:
	Light *mLight;
};

// Invoker 
// Stores the ConcreteCommand object 
class RemoteControl 
{
public:
	void setCommand(Command *cmd) {
		mCmd = cmd;
	}

	void buttonPressed() {
		mCmd->execute();
	} 
private:
	Command *mCmd;
};
 
// The client
int main() 
{
	// Receiver 
	Light *light = new Light;

	// concrete Command objects 
	LightOnCommand *lightOn = new LightOnCommand(light);
	LightOffCommand *lightOff = new LightOffCommand(light);

	// invoker objects
	RemoteControl *control = new RemoteControl;

	// execute
	control->setCommand(lightOn);
	control->buttonPressed();
	control->setCommand(lightOff);
	control->buttonPressed();

	delete light, lightOn, lightOff, control;

	return 0;
}

Output from the run:

The light is on
The light is off

We are not there yet, but let's summarize what's been done.

We know that a command object encapsulates a request by binding together
a set of actions on a specific receiver (Light).

So, a command object packages the actions (on/off) and the receiver (Light) up into an object (LightOn/OffCommand) that exposes just one method, execute().

The key to this pattern is an abstract Command class, which declares an interface for executing operations. In the simplest form this interface includes an abstract Execution operation:

// Command Interface
class Command {
public:
	virtual void execute()=0;
};

Concrete Command subclasses (LightOnCommand/LightOffCommand) specify a receiver-action pair by storing the receiver (Light) as an instance variable (mLight) and by implementing execute() to invoke the request. The receiver has the knowledge required to carry out the request.

class LightOnCommand : public Command 
{
public:
        LightOnCommand(Light *light) : mLight(light) {}
	void execute(){
		mLight->on();
	}
private:
	Light *mLight;
};

When called, execute() causes the actions to be invoked on the receiver.

(a) control->setCommand(lightOn)
(b) control->buttonPressed()
(c) RemoteControl::mCmd->execute() 
(d) LightOnCommand::execute()
(e) mLight->on()

Here, note that mCmd is a pointer to the Concrete-Command object:

Command* mCmd;

From the outside, no other objects really know what actions get performed on what receiver. They just know that if they call the execute() method, their request will be served.



Command Pattern - simple example 2

The simple example of the previous section has been extended so that we can handle several receivers. The commands bounded for each receivers are stored in vector form:

	vector<Command*> mOnCommand, mOffCommand;

Also, so called Null Object pattern has been added.

#include <iostream>
#include <vector>
using namespace std;

const int MaxCommand = 5;

enum Receiver
{
	LIGHT = 0, FAN, DOOR, OVEN, NONE
}; 

// Command Interface
class Command
{
public:
	virtual void execute() = 0;
};
 
// Receiver Class
class Light 
{
public:
	void on() {
		cout << "The light is on\n";
	}
	void off() {
		cout << "The light is off\n";
	}
}; 

// Receiver Class
class Fan
{
public:
	void on() {
		cout << "The fan is on\n";
	}
	void off() {
		cout << "The fan is off\n";
	}
}; 

// Command for turning on the light
class NullCommand : public Command 
{
public:
	void execute(){ cout << "Null command: does nothing\n"; }
};

// Command for turning on the light
class LightOnCommand : public Command 
{
public:
    LightOnCommand(Light *light) : mLight(light) {}
	void execute(){
		mLight->on();
	}
private:
	Light *mLight;
};
 
// Command for turning off the light
class LightOffCommand : public Command 
{
public:
        LightOffCommand(Light *light) : mLight(light) {}
	void execute(){
		mLight->off();
	}
private:
	Light *mLight;
};

// Command for turning on the fan
class FanOnCommand : public Command 
{
public:
        FanOnCommand(Fan *fan) : mFan(fan) {}
	void execute(){
		mFan->on();
	}
private:
	Fan *mFan;
};

// Command for turning off the fan
class FanOffCommand : public Command 
{
public:
        FanOffCommand(Fan *fan) : mFan(fan) {}
	void execute(){
		mFan->off();
	}
private:
	Fan *mFan;
};

// Invoker 
// Stores the ConcreteCommand object 
class RemoteControl 
{
public:
	RemoteControl() : mOnCommand(MaxCommand), mOffCommand(MaxCommand) {
		Command *nullCmd = new NullCommand;
		for(int i = 0; i < MaxCommand; i++) {
			mOffCommand[i] = nullCmd;
			mOnCommand[i] = nullCmd;
		}
	}
	void setCommand(Receiver id, Command *onCmd, Command *offCmd) {
		mOnCommand[id] = onCmd;
		mOffCommand[id] = offCmd;
	}

	void onButtonPressed(Receiver id) {
		mOnCommand[id]->execute();
	} 

	void offButtonPressed(Receiver id) {
		mOffCommand[id]->execute();
	} 

private:
	vector<Command*> mOnCommand, mOffCommand;
};
 
// The client
int main() 
{
	// Receiver 
	Light *light = new Light;
	Fan *fan = new Fan;

	// concrete Command objects 
	LightOnCommand *lightOn = new LightOnCommand(light);
	LightOffCommand *lightOff = new LightOffCommand(light);
	FanOnCommand *fanOn = new FanOnCommand(fan);
	FanOffCommand *fanOff = new FanOffCommand(fan);
	NullCommand *nullOn = new NullCommand();
	NullCommand *nullOff = new NullCommand();

	// invoker objects
	RemoteControl *control = new RemoteControl;

	// execute
	control->setCommand(LIGHT, lightOn, lightOff);
	control->onButtonPressed(LIGHT);
	control->offButtonPressed(LIGHT);

	control->setCommand(FAN, fanOn, fanOff);
	control->onButtonPressed(FAN);
	control->offButtonPressed(FAN);

	control->setCommand(NONE, nullOn, nullOff);
	control->onButtonPressed(NONE);

	delete light, lightOn, lightOff;
	delete fan, fanOn, fanOff;
	delete control;

	return 0;
}

Output:

The light is on
The light is off
The fan is on
The fan is off
Doing nothing






Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong





List of Design Patterns



Introduction

Abstract Factory Pattern

Adapter Pattern

Bridge Pattern

Chain of Responsibility

Command Pattern

Composite Pattern

Decorator Pattern

Delegation

Dependency Injection(DI) and Inversion of Control(IoC)

Façade Pattern

Factory Method

Model View Controller (MVC) Pattern

Observer Pattern

Prototype Pattern

Proxy Pattern

Singleton Pattern

Strategy Pattern

Template Method Pattern

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







C++ Tutorials

C++ Home

Algorithms & Data Structures in C++ ...

Application (UI) - using Windows Forms (Visual Studio 2013/2012)

auto_ptr

Binary Tree Example Code

Blackjack with Qt

Boost - shared_ptr, weak_ptr, mpl, lambda, etc.

Boost.Asio (Socket Programming - Asynchronous TCP/IP)...

Classes and Structs

Constructor

C++11(C++0x): rvalue references, move constructor, and lambda, etc.

C++ API Testing

C++ Keywords - const, volatile, etc.

Debugging Crash & Memory Leak

Design Patterns in C++ ...

Dynamic Cast Operator

Eclipse CDT / JNI (Java Native Interface) / MinGW

Embedded Systems Programming I - Introduction

Embedded Systems Programming II - gcc ARM Toolchain and Simple Code on Ubuntu and Fedora

Embedded Systems Programming III - Eclipse CDT Plugin for gcc ARM Toolchain

Exceptions

Friend Functions and Friend Classes

fstream: input & output

Function Overloading

Functors (Function Objects) I - Introduction

Functors (Function Objects) II - Converting function to functor

Functors (Function Objects) - General



Git and GitHub Express...

GTest (Google Unit Test) with Visual Studio 2012

Inheritance & Virtual Inheritance (multiple inheritance)

Libraries - Static, Shared (Dynamic)

Linked List Basics

Linked List Examples

make & CMake

make (gnu)

Memory Allocation

Multi-Threaded Programming - Terminology - Semaphore, Mutex, Priority Inversion etc.

Multi-Threaded Programming II - Native Thread for Win32 (A)

Multi-Threaded Programming II - Native Thread for Win32 (B)

Multi-Threaded Programming II - Native Thread for Win32 (C)

Multi-Threaded Programming II - C++ Thread for Win32

Multi-Threaded Programming III - C/C++ Class Thread for Pthreads

MultiThreading/Parallel Programming - IPC

Multi-Threaded Programming with C++11 Part A (start, join(), detach(), and ownership)

Multi-Threaded Programming with C++11 Part B (Sharing Data - mutex, and race conditions, and deadlock)

Multithread Debugging

Object Returning

Object Slicing and Virtual Table

OpenCV with C++

Operator Overloading I

Operator Overloading II - self assignment

Pass by Value vs. Pass by Reference

Pointers

Pointers II - void pointers & arrays

Pointers III - pointer to function & multi-dimensional arrays

Preprocessor - Macro

Private Inheritance

Python & C++ with SIP

(Pseudo)-random numbers in C++

References for Built-in Types

Socket - Server & Client

Socket - Server & Client 2

Socket - Server & Client 3

Socket - Server & Client with Qt (Asynchronous / Multithreading / ThreadPool etc.)

Stack Unwinding

Standard Template Library (STL) I - Vector & List

Standard Template Library (STL) II - Maps

Standard Template Library (STL) II - unordered_map

Standard Template Library (STL) II - Sets

Standard Template Library (STL) III - Iterators

Standard Template Library (STL) IV - Algorithms

Standard Template Library (STL) V - Function Objects

Static Variables and Static Class Members

String

String II - sstream etc.

Taste of Assembly

Templates

Template Specialization

Template Specialization - Traits

Template Implementation & Compiler (.h or .cpp?)

The this Pointer

Type Cast Operators

Upcasting and Downcasting

Virtual Destructor & boost::shared_ptr

Virtual Functions



Programming Questions and Solutions ↓

Strings and Arrays

Linked List

Recursion

Bit Manipulation

Small Programs (string, memory functions etc.)

Math & Probability

Multithreading

140 Questions by Google



Qt 5 EXPRESS...

Win32 DLL ...

Articles On C++

What's new in C++11...

C++11 Threads EXPRESS...

Go Tutorial

OpenCV...








Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master