条件を含むコードを簡素化する OO の優れた方法は、ストラテジー パターン (http://en.wikipedia.org/wiki/Strategy_pattern) を使用してそれらを置き換えることです。この特定のリファクタリングに関する情報は、http: //www.industriallogic.com/xp/refactoring/conditionalWithStrategy.htmlにあります。
基本的な考え方は、各条件付きケースのロジックを戦略でカプセル化し、代わりに戦略インスタンスに委譲することです。これにより、ネストされた if/then/else または switch ステートメントよりもはるかに明確なコードが生成されます。
この点を説明するために、次のような複雑な条件付きロジックがあると仮定しましょう。
Entity e = // some entity
if ("TypeOne".equals(e.getType()) {
// process entity of type one...
} else if ("TypeTwo".equals(e.getType()) {
// process entity of type two...
} else if ("TypeThree".equals(e.getType()) {
// process entity of type three...
} else {
// default processing logic
}
このロジックを手続き的に記述する代わりに、ストラテジー パターンを使用して、さまざまなエンティティ処理ストラテジーに分解することができます。最初に、すべてのエンティティ処理戦略から共有されるインターフェイスを定義する必要があります。
public interface EntityProcessingStrategy {
public void process(Entity e);
}
次に、条件付きケースごとに具体的な戦略の実装を作成し、特定の処理ロジックをカプセル化します。
public class TypeOneEntityProcessingStrategy {
public void process(Entity e) {
// process entity of type one...
}
}
public class TypeTwoEntityProcessingStrategy {
public void process(Entity e) {
// process entity of type two...
}
}
public class TypeThreeEntityProcessingStrategy {
public void process(Entity e) {
// process entity of type three...
}
}
public class DefaultEntityProcessingStrategy {
public void process(Entity e) {
// default entity processing logic...
}
}
したがって、前のコードは次のように条件を削除して単純化できます。
Entity e = // our entity that needs to be processed
EntityProcessingStrategy strategy = EntityProcessingStrategies.getStrategyFor(e.getType);
strategy.process(e);
最後の例では、具体的な戦略のファクトリとして機能する EntityProcessingStrategies クラスが含まれていることに注意してください。より具体的には、次のようになります。
public final class EntityProcessingStrategies {
private EntityProcessingStrategies() { }
public EntityProcessingStrategy getStrategyFor(String type) {
if ("TypeOne".equals(type)) return new TypeOneEntityProcessingStrategy();
if ("TypeTwo".equals(type)) return new TypeTwoEntityProcessingStrategy();
if ("TypeThree".equals(type)) return new TypeThreeEntityProcessingStrategy();
return new DefaultEntityProcessingStrategy();
}
}
これは、具体的な戦略インスタンスを作成する 1 つの方法ですが、決して唯一の方法ではありません。