tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Design Patterns > Java Design Patterns > Command

Command 

Command patterns comes under Behavioral design pattern. It encapsulates the complete request information as an object to defer its execution at later point.

Behaviour & Advantages

  • Separates the object from its trigger.
  • Holds complete request information to trigger at later point.
  • Needs a callback method to trigger execution.
Participants
  • Command
    Abstract interface for command execution.
  • Concrete Command
    An implementation of Command which updates Receiver's state.
  • Invoker
    It hold a reference to Concrete Command and triggers its execution.
  • Receiver
    Its the target object for Concrete Command and receives the action performed.

This example shows a simple CLI (Command Line Interface) implementation where console (System.out) acts as a Receiver and CLI acts as Invoker. The CLI supports four commands namely mm (max memory), fm (free memory), tm (total memory) and exit. These commands output a message to console (Receiver). A Concrete implementation of command object is defined supporting each command.

The Command Interface is shown below,

File Name  :  
com/bethecoder/tutorials/dp/command/ICommand.java 
   
package com.bethecoder.tutorials.dp.command;

public interface ICommand {
  
  /**
   * Execute this command
   */
  public void execute();
  
  /**
   * Command name
   @return String
   */
  public String getName();
  
  /**
   * Command description
   @return String
   */
  public String getDesc();
  
}
   

Max memory command implementation is shown below,

File Name  :  
com/bethecoder/tutorials/dp/command/MaxMemoryCmd.java 
   
package com.bethecoder.tutorials.dp.command;

public class MaxMemoryCmd implements ICommand {

  @Override
  public void execute() {
    System.out.println("System Max Memory : " + Runtime.getRuntime().maxMemory() " bytes");
  }

  @Override
  public String getName() {
    return "mm";
  }

  @Override
  public String getDesc() {
    return "System Max Memory";
  }

}
   

Free memory command implementation is shown below,

File Name  :  
com/bethecoder/tutorials/dp/command/FreeMemoryCmd.java 
   
package com.bethecoder.tutorials.dp.command;

public class FreeMemoryCmd implements ICommand {

  @Override
  public void execute() {
    System.out.println("System Free Memory : " + Runtime.getRuntime().freeMemory() " bytes");
  }

  @Override
  public String getName() {
    return "fm";
  }

  @Override
  public String getDesc() {
    return "System Free Memory";
  }

}
   

Total memory command implementation is shown below,

File Name  :  
com/bethecoder/tutorials/dp/command/TotalMemoryCmd.java 
   
package com.bethecoder.tutorials.dp.command;

public class TotalMemoryCmd implements ICommand {

  @Override
  public void execute() {
    System.out.println("System Total Memory : " + Runtime.getRuntime().totalMemory() " bytes");
  }

  @Override
  public String getName() {
    return "tm";
  }

  @Override
  public String getDesc() {
    return "System Total Memory";
  }

}
   

Exit command implementation is shown below,

File Name  :  
com/bethecoder/tutorials/dp/command/ExitCmd.java 
   
package com.bethecoder.tutorials.dp.command;

public class ExitCmd implements ICommand {

  @Override
  public void execute() {
    System.exit(0);
  }

  @Override
  public String getName() {
    return "exit";
  }

  @Override
  public String getDesc() {
    return "System Exit";
  }

}
   

Here CLI prints command listing and accepts command name as input. If user entered command name is available in the command map then triggers the command execution. Otherwise prints unknown command message to console.

File Name  :  
com/bethecoder/tutorials/dp/command/CLI.java 
   
package com.bethecoder.tutorials.dp.command;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * CLI (Command Line Interface) acts as a 
 * Command Invoker. Its registered with
 * four commands during class load. 
 */
public class CLI {
  
  private static Map<String, ICommand> commandMap = new HashMap<String, ICommand>()
  static {
    registerCommand(new MaxMemoryCmd());
    registerCommand(new TotalMemoryCmd());
    registerCommand(new FreeMemoryCmd());
    registerCommand(new ExitCmd());
  }

  private static void registerCommand(ICommand command) {
    commandMap.put(command.getName(), command);
  }
  
  public static void startCLI() {
    BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
    
    while (true) {
      showMenu();
      getAndProcessInput(console);
    }
  }
  
  private static void showMenu() {
    Iterator<String> it = commandMap.keySet().iterator();
    int cmdIndex = 0;
    String cmd;
    ICommand cmdObj;
    
    System.out.println("------ CLI Command Listing ------");
    while (it.hasNext()) {
      cmd = it.next();
      cmdObj = commandMap.get(cmd);
      System.out.println(++cmdIndex + ". " 
          cmdObj.getDesc() " (" + cmdObj.getName() ")");
    }
    System.out.println();
  }

  private static void getAndProcessInput(BufferedReader console) {
    System.out.println("Enter command : ");
    try {
      String cmd = console.readLine().trim();
      
      if (commandMap.containsKey(cmd)) {
        commandMap.get(cmd).execute();
      else {
        System.out.println("Unknown command : " + cmd);
      }
      
      System.out.println();
    catch (IOException e) {
      e.printStackTrace();
    }
  }

}
   

Command usage is shown below,

File Name  :  
com/bethecoder/tutorials/dp/command/Test.java 
   
package com.bethecoder.tutorials.dp.command;

public class Test {

  /**
   @param args
   */
  public static void main(String[] args) {
    CLI.startCLI();
  }

}
   

It gives the following output,
------ CLI Command Listing ------
1. System Max Memory (mm)
2. System Free Memory (fm)
3. System Total Memory (tm)
4. System Exit (exit)

Enter command : 
mm
System Max Memory : 66650112 bytes

------ CLI Command Listing ------
1. System Max Memory (mm)
2. System Free Memory (fm)
3. System Total Memory (tm)
4. System Exit (exit)

Enter command : 
fm
System Free Memory : 4902592 bytes

------ CLI Command Listing ------
1. System Max Memory (mm)
2. System Free Memory (fm)
3. System Total Memory (tm)
4. System Exit (exit)

Enter command : 
tm
System Total Memory : 5177344 bytes

------ CLI Command Listing ------
1. System Max Memory (mm)
2. System Free Memory (fm)
3. System Total Memory (tm)
4. System Exit (exit)

Enter command : 
exit



 
  


  
bl  br