C++ Command Pattern for Network Operations
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.
Takeaway
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:
- Create a network object.
- Create a deletion (that is, command pattern) object.
- Delete the network object.
Listing 1 Implementation of the Command Pattern
LspConnection* lsp = new LspConnection(1, 0, 1); deleteNetworkObject* deleteObject = new deleteNetworkObject(lsp); deleteObject->Execute();
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!