Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

C++ Command Pattern for Network Operations

  • Print
  • + Share This
It's all too easy to place operations code inside class definitions (that is, code that does create/delete/modify). In many cases, such an approach is not necessarily a reflection of real world objects. But there are other reasons for abstracting operation code: simplifying objects and better maintainability. Stephen Morris spells out these and other advantages of using the command pattern; including changing the operations code and providing do-undo facilities with a very modest design/coding investment.
Like this article? We recommend

The chain of responsibility pattern provides separation between events and handlers. The command pattern is conceptually similar in that it provides separation between client operations and servers. In other words, you can use the command pattern to abstract operation code away from the eventual handler. To use a common networking example, let’s assume that we want to update the code used for the configuration of a remote machine (for example, a router). This could involve calling a method such as device.updateData(), into which we pass some device-specific parameters. The command pattern allows us to separate the operation (update configuration) from the device (the router) object.

This is a powerful model because it allows for future changes in device technology without affecting the command code. On a more simplistic level, if we have a cat class, should "putting out" the cat be part of the cat class? I tend to think that putting out is part of a higher-level operation, which makes it a candidate for a command pattern.


Per most of my articles, we’ll see how the command pattern can be employed to solve a knotty problem that often is not particularly well handled in commercial products. This pattern is easily implemented and provides a surprising advantage in the form of separation of operations from the data model, which enables operations to be treated as objects in their own right. Listing 1 shows a sneak preview of the finished code, in which I do the following:

  1. Create a network object.
  2. Create a deletion (that is, command pattern) object.
  3. Delete the network object.

Listing 1 Implementation of the Command Pattern

  LspConnection* lsp = new LspConnection(1, 0, 1);
  deleteNetworkObject* deleteObject = new deleteNetworkObject(lsp);

Listing 1 shows two distinct objects: the application entity and a delete command entity. Let’s now get some background information out of the way!

  • + Share This
  • 🔖 Save To Your Account