Question

My Android application is concerned with communicating with another hardware device over a Bluetooth or USB connection. To communicate with that hardware device, it uses a command-response protocol. Each kind of command type has its own expected length of response, time-out value, what has got to be done with the response that comes back, and other parameters that are unique to each kind of command.

I decided to encapsulate everything about each type of command into a Command object, which is subclassed by each kind of Command to create concrete implementations. These objects have methods that are called to provide the initial command (series of bytes), a method to call with the response that comes back, and so on. For me this is elegant because everything about a particular command to the external hardware device, from what to send initially to how to process the response, what to do on errors, etc. is all encapsulated in a class.

Is this an example of "command pattern"?

Secondly, I have a class that is concerned with holding such Command objects in a queue and sequentially executing them (that is, sending out their command bytes via Bluetooth / USB, and calling methods on that Command to handle the response, errors, and so forth). Is there any particular pattern name for this, and what would be the best kind of class name? Perhaps CommandExecutor, CommandDispatcher?

Was it helpful?

Solution

Yes, this sounds like a standard implementation of the Command Pattern. The pattern is described e.g. in the book Design Patterns by the "Gang of Four". If you have no hardcopy at hand, you can find it online e.g. on Wikipedia or Blackwasp.

Your CommandExecutor/CommandDispatcher seem to be Invokers in the Pattern terminology. How the Invoker consumes the Commands is an implementation detail, a FIFO queue is just one way. So there is no specific name for this. But you could use another Design Pattern for this, if it matches your needs, e.g. a scheduler with or without parallel execution of the commands (see also Active Object).

Hint: If you take a look at the Pattern explanations, you will see that you have merged the Receivers and Commands into one class, since your Commands know the business logic to execute (=sending bytes, process response, etc.). So you can improve your design if you put this business logic into specific Receiver classes, which are used by the Commands. This way the Command Pattern is just a layer which uses the Receivers/business logic. This enables better testing of the business logic without taking care of the Commands as well as makes the Command Pattern exchangeable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top