Command

Introduction

The command pattern encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests, and support undoable operations.

Key Point

decouple the invoker and receiver

macro command

typical usage: queuing and logging request

Example

Considering I have a master server process to dispatch requests (add log, read database, and so on) to worker threads/processes. I can encapsulate request into an object in a work queue, each worker (thread/process) gets task from this queue, worker doesn’t care about which task it gets, it just executes command encapsulated in it.

Following demo code shows using command pattern to implement work queue. Server (command invoker) and worker (command receiver) are decoupled.

For simplicity, server and worker are just wrappered in a class and use global variable to communicate with each other. In real world, it might be multi-thread or multi-process model.