So in order to create commands (based on the pattern) in any class, that class has to know about the receiver class in order to pass it into the constructor of the command, which then couples the classes together. Is there a way to use the command pattern and keep a measure of indirection between the two classes?
The only solutions I can think of are:
- Use a mediator, but how exactly I don’t know since at the least the command would still need to be passed the class even if it was just its interface
- Use a facade, but that couples any command calling class to the facade
- Use an event system instead of commands, but that has too much overhead in execution and just writing the code itself
- Use a creation pattern to make the commands somehow but that couples everything to that object
My biggest concern with the event system is that from my experience with event systems the amount of code you have to write to get the sender and receiver interacting without knowing about each other is insane and not practical at all- every method I want accessible by an event requires me to modify at least one other class and usually more, which creates problems just as bad as tightly coupled spegetti code. Also I usually need classes to send responses to events which is also very cumbersome.
The command pattern isn’t meant to decouple the creator and the receiver; these classes are usually already coupled or may even be the same class.
What the command pattern does is decouple the implementation from the class which executes the command. Once the command has been created, it can be passed to the UI layer or over the network to a remote client, and the executing class does not require any knowledge of how the command is implemented.