Please somebody clears me up the mess in my head with these patterns:
- Chain of Command
- Chain of Responsibility
I’ve seen sites in which both are the same (examples of Chain of Command which are the same as Chain of Responsibility), and other sites in which not.
This is what I understand about each:
CHAIN OF COMMAND:
A class let’s call it CommandChain, with a property holding a list of “commands”, which are instances of classes which implement the same interface. Say they all must implement onCommand(command, arguments).
CommandChain has the addCommand() method to register new commands within it, and runCommand() which accepts a command name, and its parameters. This method should loop through the list of commands until one of them responds, does the corresponding actions, and sends ok.
CHAIN OF RESPONSIBILITY
Just as I’ve seen in some sites, this would be pretty much the same, with this difference:
instead of having a class storing a list of commands to loop through, each command instance would store a reference to the next command instance.
So, is this difference big enough to consider both design patterns different?
In what real cases are they applicable?
They are the same design pattern.
If they have the same properties and only the implementation differs, they are functionally the same. This indicates that the two design patterns are one and the same.
Another hint is that there is a Wikipedia page for Chain of Responsibility DP, but none for Chain of Command.
The “Gang of Four” who wrote the seminal book on DPs were very clear on that behavior and properties, not implementation, defined a design pattern.