且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当“if else”/“实例”是不可避免的,除了使用访客模式,我们如何改进设计?

更新时间:2023-12-01 19:48:46

如果你仍然知道编译时的类型,你可以使用一个帮助类:

If you still know the types at compile time you can use a helper class:

class Function {
}

class Average extends Function {
}

class Sum extends Function {
}

class Max extends Function {
}

class FunctionHelper {
  public Number calculate(Average a) {
    return null;
  }

  public Number calculate(Sum s) {
    return null;
  }

  public Number calculate(Max a) {
    return null;
  }

  public Number calculate(Function a) {
    return null;
  }

}

一般来说,你会帮助方法是静态的,但你并不局限于这些 - 有一些相当有趣的事情,你可以使用多种助手类。

Generally you'd make the helper methods static but you are not restricted to that - there are some rather interesting things you can do with multiple flavours of helper class.