Apex Design Patterns(Strategy)
8157 ワード
1.Strategyの概要
戦略パターン(別名ポリシーパターン)は同じ問題に対して複数の解決策を提供する。
実行時に1つの解決策を選択する。
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.参照資料
public interface Strategy {
Integer operation(Integer num1, Integer num2);
}
public class OperationAdd implements Strategy{
public Integer operation(Integer num1, Integer num2) {
return num1 + num2;
}
}
public class OperationSubstract implements Strategy{
public Integer operation(Integer num1, Integer num2) {
return num1 - num2;
}
}
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);
}
}
System.debug('10 + 5 = ' + Context.executeStrategy('OperationAdd', 10, 5));
System.debug('10 - 5 = ' + Context.executeStrategy('OperationSubstract', 10, 5));
Author And Source
この問題について(Apex Design Patterns(Strategy)), 我々は、より多くの情報をここで見つけました https://qiita.com/xuwenzhen/items/e6b6df9eb9b9b1d62a79著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .