Code, JavaEE

Using Commands

Command Steps:

  • Define a command marker interface
  • Define a command data holder
  • Define a command handler that takes a command as a parameter
  • Define an execute method with a command for the command handler
  • Define a concrete command and command handler and unit test

 


package commands;

/**
 * CommandHandler
 *
 * @author david.king
 */
public interface CommandHandler<Command> {

public void execute(Command command);

}

&nbsp;

package commands;

/**
 * Command
 *
 * @author david.king
 */
public interface Command {

}

&nbsp;

package commands;

/**
 * CreateUserCommand
 *
 * @author david.king
 */
public class CreateUserCommand implements Command {
 public String id;
 public String username;
 public String password;

public CreateUserCommand() {}

public String getId() {
 return id;
 }

public void setId(String id) {
 this.id = id;
 }

public String getUsername() {
 return username;
 }

public void setUsername(String username) {
 this.username = username;
 }

public String getPassword() {
 return password;
 }

public void setPassword(String password) {
 this.password = password;
 }
}

&nbsp;

package commands;

/**
 * CreateUserHandler
 *
 * @author david.king
 */
public class CreateUserHandler implements CommandHandler<CreateUserCommand> {
 @Override
 public void execute(CreateUserCommand createUserCommand) {
 System.out.println("Validating user information");
 System.out.println("Provisioning user on backend");
 System.out.format("CreateUserHandler done for username %s", createUserCommand.username);
 System.out.println("Putting results message on appropriate queue");
 }
}

&nbsp;

package principles;

import commands.Command;
import commands.CommandHandler;
import commands.CreateUserCommand;
import commands.CreateUserHandler;
import org.junit.Test;

import java.util.UUID;

/**
 * CommandTest
 *
 * @author david.king
 */
public class CommandTest {

@Test
 public void testCreateUser() {
 CreateUserCommand createUserCommand = new CreateUserCommand();
 createUserCommand.id = UUID.randomUUID().toString();
 createUserCommand.username = "davidking";
 createUserCommand.password = "davidking";

CommandHandler commandHandlerCreateUser = new CreateUserHandler();
 commandHandlerCreateUser.execute(createUserCommand);
 }
}

 

Ref: http://ben.onfabrik.com/posts/crud-do-better

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s