Apex Design Patterns(Strategy)


1.Strategyの概要

戦略パターン(別名ポリシーパターン)は同じ問題に対して複数の解決策を提供する。
実行時に1つの解決策を選択する。

UML構造図

2.実装例

2.1.Strategyインターフェース作成


public interface Strategy {
    Integer operation(Integer num1, Integer num2);
}

2.2.OperationAddクラス作成


public class OperationAdd implements Strategy{
    public Integer operation(Integer num1, Integer num2) {
       return num1 + num2;
    }
}

2.3.OperationSubstractクラス作成


public class OperationSubstract implements Strategy{
    public Integer operation(Integer num1, Integer num2) {
       return num1 - num2;
    }
}

2.4.Context クラス作成


public class Context {
    public class NameException extends Exception{}
    private static Map<String, Strategy> strategyMap = new Map<String, Strategy>();

    static {
        strategyMap.put('OperationAdd', new OperationAdd());
        strategyMap.put('OperationAdd', new OperationSubstract());
    }

    public static Integer executeStrategy(String strategyName, Integer num1, Integer num2){
        if (!strategyMap.containsKey(strategyName)) {
            throw new NameException(String.format('strategyが存在しません({0})', new String[]{strategyName}));
        }

        Strategy strategy = strategyMap.get(strategyName);
        return strategy.operation(num1, num2);
    }
}

2.5.Client


System.debug('10 + 5 = ' + Context.executeStrategy('OperationAdd', 10, 5));  
System.debug('10 - 5 = ' + Context.executeStrategy('OperationSubstract', 10, 5));

3.参照資料