Thursday, November 5, 2015

Design Patterns - Command Pattern



https://dzone.com/articles/design-patterns-command
http://javapapers.com/design-patterns/command-design-pattern/

The following information is copied from the above links..


Image title



Command declares an interface for all commands, providing a simple execute() method which asks the Receiver of the command to carry out an operation.

java.lang.Runnable
javax.swing.Action


  • Command is an interface with execute method. It is the core of contract.
//Command
public interface Command{
  public void execute();
}


  • A Command implementation’s instance creates a binding between the receiver and an action
//Concrete Command
public class LightOnCommand implements Command{
  //reference to the light
   Light light;
  public LightOnCommand(Light light){
     this.light = light;
}
  public void execute(){
     light.switchOn();
}
}



//Concrete Command
public class LightOffCommand implements Command{
  //reference to the light
  Light light;
  public LightOffCommand(Light light){
    this.light = light;
  }
  public void execute(){
    light.switchOff();
  }
}


  • Receiver is the object that knows the actual steps to perform the action.
Receiver Class

//Receiver

public class Light{
  private boolean on;
  public void switchOn(){
    on = true;
  }
  public void switchOff(){
    on = false;
  }
}

  • An invoker instructs the command to perform an action.

//Invoker
public class RemoteControl{
  private Command command;
  public void setCommand(Command command){
    this.command = command;
  }
  public void pressButton(){
    command.execute();
  }
}

  • A client creates an instance of a command implementation and associates it with a receiver.
//Client
public class Client{
  public static void main(String[] args)    {
    RemoteControl control = new RemoteControl();
    Light light = new Light();
    Command lightsOn = new LightsOnCommand(light);
    Command lightsOff = new LightsOffCommand(light);
    //switch on
    control.setCommand(lightsOn);
    control.pressButton();
    //switch off
    control.setCommand(lightsOff);
    control.pressButton();
  }
}



No comments: