Java 设计咨询:从多个类调用方法
我正在解决一个问题,在这个问题中,我将从用户处获得以下形式的输入Java 设计咨询:从多个类调用方法,java,oop,Java,Oop,我正在解决一个问题,在这个问题中,我将从用户处获得以下形式的输入 { "serviceA":true, "serviceB":true, "serviceC":false, "serviceD":true, "serviceE":false, "score":10 } 根据用户选择,我需要调用服务收集分数。此服务调用将更新分数,然后按一定幅度进行更新。 我为所有这些服务制作了套餐 这里的一个约束条件是,它们是连续的,即如果两者都启用,则只能在A之后调用B,否则可以直接调用B 我正在使用一个构建
{
"serviceA":true,
"serviceB":true,
"serviceC":false,
"serviceD":true,
"serviceE":false,
"score":10
}
根据用户选择,我需要调用服务收集分数。此服务调用将更新分数,然后按一定幅度进行更新。
我为所有这些服务制作了套餐
这里的一个约束条件是,它们是连续的,即如果两者都启用,则只能在A之后调用B,否则可以直接调用B
我正在使用一个构建器文件,其中我将获得上面提到的所有服务标志的初始分数。然后我需要使用此分数调用所有服务方法。如果我把这个分数传给了服务A,那么服务B也需要知道服务A的分数 使用责任链设计模式,我会这样做
interface ServiceInterface {
public int getScore(int score);
}
class service implements ServiceInterface {
private boolean enabled;
private int factor;
private ServiceInterface nextService = null;
public serviceA(boolean enabled, int factor){
this.enabled = enabled;
this.factor = factor;
}
public void setNextService(ServiceInterface service){
this.nextService = service;
}
@Override
public int getScore(int score) {
if (this.enabled)
score = score * this.factor;
if (nextService != null)
score = nextService.getScore(score);
return score;
}
}
一个简单的运行示例是
int score = 10;
service a = new service(false, 4);
service b = new service(true, 3);
a.setNextService(b);
System.out.println(a.getScore(score));
输出
30
这将a->b
定义为链,并调用a的getScore
,而不是b的getScore
,这将根据enable
变量计算分数或跳过
您还可以使用继承并将更多方法移动到接口
我需要调用用于分数收集的服务
->什么是服务方法?它的输入/输出是什么建议您看看责任链设计模式