Java - Getter/Setter、行为和接口

Dr1*_*231 5 java code-structure getter-setter

我有一个问题,有点理论:

假设,我有以下课程:

interface ReportInterface {
     void execute();
}

class Report implements ReportInterface {

  private final Repository rep; 

  Report(Repository ref){
     this.rep = ref;
  }

  public void execute(){
     //do some logic
  }
}


class ReportWithSetter implements ReportInterface {

  private final Repository rep;
  private String release;

  ReportWithSetter(Repository ref){
     rep = ref;
  }

  public void execute(){
     if (release == null) throw IlligalArgumentException("release is not specified");
     //do some logic
  }
  
  public void setRelease(String release){
     this.release=release;
  }
}

Run Code Online (Sandbox Code Playgroud)

第二个报告需要一个额外的参数释放才能正常工作,但我的接口定义为没有execute方法参数,所以我使用 setter 方法解决它,所以它看起来像:

ReportWithSetter rep2 = new ReportWithSetter (rep);
rep.setRelease("R1.1");
rep.execute();
Run Code Online (Sandbox Code Playgroud)

所以我不喜欢这个额外的rep.setRelease. 我看起来很奇怪和做作 - 这个类的用户可能会感到困惑,例如,如果我在 Spring 中将该类作为单例 bean,它是潜在错误的来源,如果它被第二次请求而有人忘记了rep.setRelease第二次触发。除了将它放入构造函数(我想将它变成一个 spring bean)之外,处理这种情况的最佳做法是什么?

Kar*_*tik 5

假设您可以更改界面,这里有一些我能想到的解决方案:

解决方案#1

void execute(Optional<String> release);
Run Code Online (Sandbox Code Playgroud)

或者

void execute(@Nullable String release);
Run Code Online (Sandbox Code Playgroud)

然后将它们用于Report类 as execute(Optional.empty())or execute(null)

解决方案#2

void execute(String... release);
Run Code Online (Sandbox Code Playgroud)

然后将它用于Reportclass asexecute()ReportWithSetterclass as execute("R1.1")

解决方案#3

在界面中定义void execute();void execute(String release);。然后在实现的时候,把UnsupportedOperationException你不需要的方法扔进去。例如,在Report课堂上,你会这样做:

  public void execute(){
     //do some logic
  }

  public void execute(String release){
     throw new UnsupportedOperationException("Use the overloaded method");
  }
Run Code Online (Sandbox Code Playgroud)

您还可以default在接口中创建这两个方法,因此您的实现类不必担心实现不受支持的方法。


使用对您来说最易读和最易于维护的那个。