0

可能重复:
Java 方法重载 + 双分派

可能是一个愚蠢的新手问题:。我想在这样的情况下避免使用 instanceof 运算符:

class Service {
  method(Some param) {  }
}

class Special extends Some { }

class SpecialService extends Service {
  method(Some param) {
    if (param instanceof Special) {
      //do special things 
    }
  }

  method(Special param) {
    //do special things 
  }

}

第二种特殊方法是避免 instanceof 的正确方法吗?

服务的调用方会不会有问题?在我的情况下,特殊服务是一个定制版本,插入并从基本代码调用。将调用哪个方法?

Service s = new SpecialService();
s.method(specialparam);

请指出我如何解决这个问题的紧凑描述或模式。似乎是基本的Java/OO知识...

4

2 回答 2

0

I'm not sure durron597 is right. It all depends on how your code is written. It would workautomatically only if both variables are declared using specific types:

//good
Special specialparam = new Special();
SpecialService s = new SpecialService();
s.method(specialparam);

Code like

//bad
Some specialparam = new Special();
SpecialService s = new SpecialService();
s.method(specialparam);

or like

//bad
Special specialparam = new Special();
Service s = new SpecialService();
s.method(specialparam);

wouldn't work as you expect because known compile-time types are used to select method.

The whole design looks suspicously. This might be the right way but probably it is worths reconsidering it.

One of things that might hepl is Double dispatch mentioned by dasblinkenlight's comment. But to do one of base classes (Some or Service) should know about special cases. In short idea is that you write something like this:

class Some {
  public void dispatch(Service service)  {
    service.method(this);
  }
}

class Special extends Some { 
  public void dispatch(Service service)  {
    service.method(this);
  }
}



class Service {
  void dispatch(Some some) {
      some.dispatch(this);
  }


  void method(Some some) {
     // do common things here  
  }

  void method(Special some) {
     method((Some)some);
  }
}

class SpecialService extends Service {

  method(Special param) {
    //do special things 
  }
}
于 2012-12-07T18:25:09.523 回答
0

Java 会自动执行此操作。您的代码将完全按照您的意愿工作,无需 if 语句。在选择要执行的方法版本时,Java 会选择最具体(最子类化)的方法签名。

这是一篇关于这个主题的非常好的文章。

于 2012-12-07T16:38:39.123 回答