2012-11-27 69 views
0

我需要解释代码..你能帮我吗?

下面的代码取自一个网站。它是命令模式的示例代码。我们有Ligth类作为Receiver。

为什么他们在FillUpCommand()和FlipDownCommand()中传递了“lamp”对象作为参数?

为什么他们定义了公共FlipUpCommand(Light light)和FlipDownCommand(Light light)?

命令设计模式

/* The Command interface */ 


    public interface Command { 
     void execute(); 
    } 

    import java.util.List; 
    import java.util.ArrayList; 

    /* The Invoker class */ 
    public class Switch { 
     private List<Command> history = new ArrayList<Command>(); 

     public Switch() { 
     } 

     public void storeAndExecute(Command cmd) { 
      this.history.add(cmd); // optional 
      cmd.execute();   
     } 
    } 

    /* The Receiver class */ 
    public class Light { 
     public Light() { 
     } 

     public void turnOn() { 
      System.out.println("The light is on"); 
     } 

     public void turnOff() { 
      System.out.println("The light is off"); 
     } 
    } 

    /* The Command for turning on the light - ConcreteCommand #1 */ 
    public class FlipUpCommand implements Command { 
     private Light theLight; 

     public FlipUpCommand(Light light) { 
      this.theLight = light; 
     } 

     public void execute(){ 
      theLight.turnOn(); 
     } 
    } 

    /* The Command for turning off the light - ConcreteCommand #2 */ 
    public class FlipDownCommand implements Command { 
     private Light theLight; 

     public FlipDownCommand(Light light) { 
      this.theLight = light; 
     } 

     public void execute() { 
      theLight.turnOff(); 
     } 
    } 

这是主类..

/* The test class or client */ 
    public class PressSwitch { 
     public static void main(String[] args){ 
      Light lamp = new Light(); 
      Command switchUp = new FlipUpCommand(lamp); 
      Command switchDown = new FlipDownCommand(lamp); 

      Switch s = new Switch(); 

      try { 
      if (args[0].equalsIgnoreCase("ON")) { 
       s.storeAndExecute(switchUp); 
       System.exit(0); 
      } 
      if (args[0].equalsIgnoreCase("OFF")) { 
       s.storeAndExecute(switchDown); 
       System.exit(0); 
      } 
      System.out.println("Argument \"ON\" or \"OFF\" is required."); 
      } catch (Exception e) { 
      System.out.println("Arguments required."); 
      } 
     } 
    } 

回答

0

为什么他们在FillUpCommand()和FlipDownCommand通过了 “灯” 对象作为参数() ? 为什么他们定义了公共FlipUpCommand(Light light)和FlipDownCommand(Light light)?

灯对象被传递给构造函数,以便这些命令知道它们控制哪个灯。

Providing a Constructor tutorial