这是一个问题陈述:我们有接口/超级班学生和教师
学生有两个实现/子分支,ScienceStudent和PhysicalEducationStudent
老师有ScienceTeacher和PhysicalEducationTeacher.
我们想要实现一个方法getMeetingPoint(Student,Teacher t),它根据学生和教师的类型返回他们见面的地方.
举例来说,如果其ScienceStudent和ScienceTeacher他们在满足实验室 如果PEStudent和体育教师,他们在满足地面,如果它的一个ScienceStudent和体育教师,反之亦然,他们在满足食堂
我们可以写一个天真的方法,检查使用instanceof.但问题是,当教师或学生扩展并且难以维护时,这变得复杂.这样的事情:
public class MeetingPointDecider {
getMeetingPoint(Student s,Teacher t) {
if(s instanceof ScienceStudent && t instanceof ScienceTeacher) {
return "Lab";
} else if (s instanceof PhysicalEducationStudent && t instanceof PhysicalEducationTeacher) {
return "GRound";
}
.
.
.
}
}
Run Code Online (Sandbox Code Playgroud)
另一个选择是写一个工厂,它接受一个学生和一个教师,并返回类似MeetingPointDecision [Ground或Lab],但问题仍然存在.我们可以使用任何好的模式,在添加新类时我们不必修改现有的类(或最小的修改),Say instanceofScienceStudent我们有ChemistryStudent,PhysicsStudent和ChemistryLab,PhysicsLab.还有可能添加更多操作,这些操作根据学生和教师类型的不同而有所不同(其中访问者是一个选项,但不确定如何使用两个决定类来实现)
有人可以建议一个好方法来实现这个吗?
谢谢!
我正在调用一个返回CompletableFuture的服务.
输出结构如下.
Class Output {
public String name;
public Integer age;
}
Run Code Online (Sandbox Code Playgroud)
我想打电话给服务,并希望继续我的执行,直到名字出现.
就像是,
CompletableFuture<Output> futureOutput = makeServiceCall(input);
String name = futureOutput.get().name;
processName(name); // which will do some costly operations and make use of the name at the end.
Run Code Online (Sandbox Code Playgroud)
在上面的方法中,我需要等到我futureOutput准备好了,即使我以后只需要它.
我寻找类似下面的方法.
CompletableFuture<Output> futureOutput = makeServiceCall(input);
CompletableFuture<String> futureName = futureOutput.get().name; // This is wrong, but can we create a reference in a similar way?
processName(futureName); // which will do some costly operations and make use of the name at …Run Code Online (Sandbox Code Playgroud)