为什么传递一个Command对象不起作用?

时间:2012-01-08 09:17:45

标签: java gwt

我想知道为什么将父级子类的两级Command对象传递不起作用。

像这样(A类是B的父级,B是B的父级):

Class A (Creates the instance of the Command object that is passed down to B)

+-- Class B ( Pass down the object to C) 


+------- Class C ( Callsthe execute() method of the Command object)

然而,当在B类中创建Command对象的实例并向下传递给C类时,它可以正常工作。

示例:

编辑:

示例(手写代码):

public class A {
   private Command command;
   private B b;
   public A() {
     b = new B();
     command = new Command() {
          public void execute() {
            // Do something
          }
     }
     b.setCommand(command);
   }

public class B {
   private Command command;
   private C c;

   public B() {
     c = new C();
     c.setCommand(this.command);
   }

   public void setCommand(Command command){
       this.command = command; 
   }  

}


public class C {
   private Command command;
   public C() {

   }

   public void doStuff() {
       command.execute();
   }
   public void setCommand(Command command){
       this.command = command; 
   }        
}

4 个答案:

答案 0 :(得分:2)

从您的示例代码中可以看出,当您调用c.setCommand()时(在B的构造函数中),this.command尚未使用从A传递的Command实例进行更新:

b = new B();
// here, c.setCommand() has already been called with b.command, which hasn't been initialized, so is 'null'
b.setCommand(command); // sets b.command, but doesn't change c.command's value, which is then still 'null'

使用调试器逐步执行代码会在几秒钟内显示错误的来源。这是Java 101。

答案 1 :(得分:1)

Command对象的访问修饰符是公开的吗?

答案 2 :(得分:0)

问题是在传递过程中,来自A类的Command对象被分配给B类的本地Command对象,这是B类的本地Command对象被发送到C类。

答案 3 :(得分:0)

哦......你需要进一步了解对象实例化的顺序。

  • 您实例化了B对象。
  • 然后在C对象的实例化中,为C对象分配B对象的命令。
  • 当时命令为空。
  • 然后只有你为B对象分配了一个命令,这已经太晚了,因为你应该把命令传递给B的构造函数。

A类:

public class A {
   private B b;
   public A() {
     b = new B(
       new Command() {
         public void execute() {
           Window.alert("Gotcha");
         }
       }
     );
   }

B组:

public class B {
   private C c;

   public B(Command cmd) {
     c = new C();
     c.setCommand(cmd);
     c.doStuff();
   }
}

C类:

public class C {
  private Command command;
  public C() {
  }

  public void doStuff() {
    command.execute();
  }

  public void setCommand(Command command){
    this.command = command; 
  }        
}

或者,为什么不呢?

public class B {
   private C c;

   public B(Command cmd) {
     c = new C(cmd).doStuff(1000);
   }
}

public class C {
  private Command command;
  public C(Command cmd) {
    this.command = cmd; 
  }

  public C doStuff(int i) {
    if (--i>0){
      new C(cmd).doStuff(i);
    }    
    command.execute();
    return this;
  }
}