Ale*_*lls 0 java design-patterns return return-value
说我调用了一个方法。我想要该方法的返回值。但是,此方法将任务委托给其他方法,而这些方法又可能将任务委托给其他方法。最顶层方法最终返回的值最终由子方法和子方法的子方法决定。
想象一下这个场景:
public String method1(Object o){
if(x)
return subMethod1(o);
if(y)
return subMethod2(o);
if(z)
return subMethod3(o);
else
return "";
}
Run Code Online (Sandbox Code Playgroud)
//示例子方法
public String subMethod1(Object o){
if(a)
return subSubMethod1(o);
if(b)
return subSubMethod2(o);
if(c)
return subSubMethod3(o);
else
return "";
}
Run Code Online (Sandbox Code Playgroud)
//示例子子方法
public String subSubMethod1(Object o){
//etc etc
return "";
}
Run Code Online (Sandbox Code Playgroud)
这对我来说是一个反复出现的问题,我希望有一种设计模式可以解决此类问题。
有这样的设计模式吗?
如果你真的想使用设计模式,责任链是我能想到的最接近你的情况的模式。但这很快就会过火
public interface Handler{
void setNext(Handler h);
String handle(Object o);
}
public class Method1Handler implements Handler{
private Handler next;
@Override
public void setNext(Handler h){
this.next= h;
}
@Override
public String handle(Object o){
if(x){
return subMethod1();
}else if(next !=null){
return next.handle(o);
}
return "";
}
}
Run Code Online (Sandbox Code Playgroud)
当然subMethod1()也会使用 CoR 等。它可能会变得非常丑陋,但顶级是干净的:
//top level of code
Method1Handler handler = new Method1Handler();
//...lots of set next
//...and set next of nexts etc
//...
return myHandler.handle(o);
Run Code Online (Sandbox Code Playgroud)