在 Java 中测试开闭原则

Testing Open-Close principle in Java

为了演示SOLID原理的Open/Closed原理,我实现了如下代码。

代码:

interface IFaculty{
    void admin();
}

class ITFac implements IFaculty{
    @Override
    public void admin() {
        System.out.println("IT Fac Admin");
    }
}

class MedFac implements IFaculty{
    @Override
    public void admin(){
        System.out.println("Med Fac Admin");
    }
}

class University{
    public void adminFaculty(IFaculty iFaculty){
        iFaculty.admin();
    }
}

为了测试上面的代码,我尝试在mainclass的main方法中调用adminFaculty()方法如下

代码:

public class Main {
    public static void main(String[] args) {
        University u1 = new University();
        u1.adminFaculty();   // cannot call this method without passing parameters
    }
}

但是我不能在不传递相关参数的情况下调用该方法:IFaculty 的一个对象。但我不能这样做。有人知道如何从 main 方法调用 adminFaculty() 吗?或调用 adminFaculty() 和 运行 代码以提供相关输出的任何方式。?

谢谢。

根据您的问题,我假设您希望能够调用 adminFaculty() 并始终使用相同的教员。为此,不要将 faculty 传递给该方法,而是在 University 中保留一个引用。您还可以添加默认教员。

class University {
  private IFaculty faculty;

  //default configuration of the university: it has a medical faculty
  public University() {
    this(new MedFac());
  }

  //allows to create a university with another faculty type
  public University( IFaculty faculty) {
    this.faculty = faculty;
  }

  public void adminFaculty(){
    faculty.admin();
  }
}

现在你可以这样使用了:

University medicalUni = new University();
medicalUni.adminFaculty();

University anotherMedicalUni = new University(new MedFac());
anotherMedicalUni.adminFaculty();

University itUni = new University(new ITFac());
itUni.adminFaculty();

请注意,您始终 需要 IFaculty 的实现,例如 MedFacITFac。当然,我现在可以添加新教员而无需更改 University:

class TechFac implements IFaculty{
  @Override
  public void admin() {
    System.out.println("Tech Fac Admin");
  }
}

University techUni = new University(new TechFac());