An SO User
An SO User

Reputation: 24998

Command Pattern basics

Suppose I have a file with contents like this, which is a combination of some config information and some commands:

server1 192.168.0.1  
server2 192.168.0.12  
file1 /home/user1/file1  
upload file1 to server1  
ping server1  
replicate server1
shutdown server1  

The command pattern is well-suited to this as each of "upload", "ping", "replicate", and "shutdown" can be represented as a command.

However, I still have a few questions:

1. Whose responsibility is it to parse the input?
The input file has necessary information like where the files and servers are. Who will do the parsing? Client? Receiver? Invoker?

2. Where should the parsed information be stored?
The parsed information from first 3 lines would go in a HashMap. According to DZone's blog post,

The Receiver has the knowledge of what to do to carry out the request.

So, I am guessing Receiver is the one where the HashMap will stored?

3. Can commands return results?
Commands like "ping" or "shutdown" should indicate what happened after the command was executed. Can these commands return values?

Upvotes: 2

Views: 144

Answers (1)

user996142
user996142

Reputation: 2883

  1. Whose responsibility is it to parse the input?

Each line has 2 parts: command name, and arguments. Arguments are command-specific, so you should have CommandsProvider that should:

  • Split file to lines
  • For each line separate first word and other words
  • Create command according to first word (you may have CommandsRegistry that knows how to find command by its name)
  • Provide all arguments to command

Command PingCommand knows its first argument is server. In theory, you may pair each command with ArgumentsParser that takes array of words and configures command with it, but not sure it is necessary.

  1. Where should the parsed information be stored?

Information is stored in command, receiver simply executes it.

  1. Can commands return results?

Yes, you can implement execute() method as you like.

Upvotes: 3

Related Questions