我認為你應該使用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’.