オンドレイ・Sotolar:
あなたが特定の順序で一連のアクションを実行する必要がある場合には、Chain of Responsibilityパターンは、条件の順序のための良い代替品ですか?このような条件で簡単な方法を交換することをお勧めします:
public class MyListener implements MyHttpListener {
// if false, the request will be thrown away and subsequent listeners will not be notified
@Override
public boolean onHttpRequestSend(HttpMessage msg) {
// handlers can change msg
boolean isA = handleA(msg);
if (isA) return false;
boolean isB_notA = handleB(msg);
if (isB_notA) return false;
boolean isC_notA_notB = handleC(msg);
if (isC_notA_notB) return true;
...
throw new IllegalStateException();
}
}
今、Chain of Responsibilityパターンの実装に置き換えます。
public class MyListener implements MyHttpListener {
@Override
public boolean onHttpRequestSend(HttpMessage msg) {
ProcessingStep first = new StepA()
ProcessingResult result = first.process(new ProcessingResult(msg, true));
return result.returnValue;
}
}
public interface ProcessingStep {
ProcessingResult process(ProcessingResult stepResult);
}
public class ProcessingResult {
HttpMessage message;
boolean returnValue;
}
public class StepA implements ProcessingStep {
@Override
public ProcessingResult process(ProcessingResult stepResult) {
if (handleA()) {
return stepResult;
}
else {
return new StepB().process(stepResult);
}
}
}
public class StepB implements ProcessingStep {
@Override
public ProcessingResult process(ProcessingResult stepResult) {
return stepResult; // this is the last step
}
}
表示名 :
責任のチェーンは、あなたがのチェーン交換、すなわち、記述されていることを正確なシナリオのためのものですif ... else
(に包まれたあなたの要求ハンドル1回の呼び出しでmsg
あなたの例では)。
だから、答えは:はい、2番目のコードは、あなたの最初のコードの良い代替品です。
あなたが二番目で、コードのあなたの最初の部分を交換する必要がありますかどうかは別の問題です。あなたが現在持っているものとして、単純なように、コードの場合は、デザインパターンを追加することは行き過ぎかもしれません。このパターンを使用するための補助的な理由は以下のとおりです。
- 動的な構成
if ... else
ブロック。 - 新しい処理ブロックを追加します。
- ハンドラを再利用ディスパッチャ送出することが可能な、
msg
成形、様々な方向に責任のツリー。
- それはデザインパターンを要求するようなあなたの状況はと思われる場合は、先に行きます。
- そうでない場合は、それを残します。
- あなたは疑問がある場合、今のパターンを追加します。将来的にはあなたが/あなたのチームメイトは、あなたのコードについて混乱表示された場合、その時点でそれを削除。