mardi 15 septembre 2015

Why should I use Command design pattern while I can easily call required methods?

I am studying command design pattern, and I am quite confused with the way of using it. The example that I've found is related to a remote control class that is used to turnon and turnoff lights. My question is why I do not use the switchOn() / switchOff() methods rather than having separate classes and methods that eventually call switchOn / switchOff methods?

//Command
public interface Command{
  public void execute();
}

//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();        //explicit call of selected class's method
  }
}

//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
public class Light{
  private boolean on;
  public void switchOn(){
    on = true;
  }
  public void switchOff(){
    on = false;
  }
}

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

//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();
  }
}

Why should not I easily use a code like following:

 Light light = new Light();
 switch(light.command){
  case 1:
    light.switchOn();
    break;
  case 2:
    light.switchOff();
    break;
 }

Aucun commentaire:

Enregistrer un commentaire