我认为你应该使用GoF模式
Chain of responsibility.你应该引入两个接口:1)你将检查正确条件的条件,例如“如果zip文件不存在”并返回布尔结果 – 如果条件满足则返回“true”,否则“else”,2)执行策略,它将运行分配有条件的动作,例如: “从指定的URL下载它然后解压缩并读入文件并将zip文件移动到指定的目录.”因此,第一个界面将回答“何时”,第二个 – “然后”. “条件”实现和“执行策略”实现应该组合成“元组”(或对,条目等).这个“元组”应该按照你所描述的顺序移动到集合中.然后,当您需要处理zip文件时,您将迭代收集,调用条件和检查结果,如果结果为“true”,则调用适当的“执行策略”.此外,条件可以与执行策略结合,并通过两种方法转移到单个接口/实现中.上下文,将描述zip文件的当前状态,可以在条件/执行策略之间传递.
希望这可以帮助.
更新.
代码示例(在Java中).
/**
* All implementations should check proper condition
*/
interface Condition {
/**
* Check if condition is satisfied
*
* @param pathToFile path to target file
* @return 'true' if condition is satisfied,otherwise 'false'
*/
boolean isSatisfied(String pathToFile); //i've made an assumption that you'll manipulate file path for checking file
}
...
/**
* Childs will wrap some portion of code (if you'll use language,that supports lambdas/functors,this interface/implementation can be replaced with lambda/functor)
*/
interface Action {
/**
* Execute some portion of code
*
* @param pathToFile path to target file
*/
void execute(String pathToFile);
}
...
class ZipFileExistsCondition implements Condition {
@Override
public boolean isSatisfied(String pathToFile) {
... //check if zip file exists
}
}
...
class ZipFileDoesNotExists implements Condition {
@Override
public boolean isSatisfied(String pathToFile) {
... //download zip file and move it to some temp directory
//if file downloaded ok,than return 'true' otherwise 'false'
}
}
...
class AlwaysSatisfiedCondition implements Condition {
@Override
public boolean isSatisfied(String pathToFile) {
... //always returns 'true',to run action assigned with this condition
}
}
...
Collection> steps = Arrays.asList(
new AbstractMap.ImmutableEntry(new ZipFileExistsCondition(),new Action() { /*move zip file to zip file directory and read in file*/ }),new ZipFileDoesNotExists(),new Action() { /*download it from specified URL and then unzip it and read in file and move zip file to specified directory*/ },new AlwaysSatisfiedCondition(),new Action() { /*create blank file and write it out to disk*/ }
);
...
String pathToFile = ...
...
for(Map.Entry step: steps) {
if(!step.getKey().isSatisfied(pathToFile))
continue;
step.getValue().execute(pathToFile);
}
备注:
1)您可以将’Condition’实现为匿名类,
2)’AlwaysSatisfiedCondition’可以是单身,
3)如果你使用的是Java / Groovy / Scala,你可以使用Guava / Apache Commons的’Predicate’而不是’Condition’,’Function’或’Closure’而不是’Action’.
如果您需要在第一个’满意’条件和适当的操作执行后退出,那么只需在执行动作后放入’break’/’return’.