Spring-策略模式

设计模式
public interface Strategy {
  Object verificate(StrategyBo strategyBo);
}
1
2
3
@Component("aStrategy")
public class AStrategy implements Strategy {
  @Override
  public Object verificate(StrategyBo strategyBo) {
    // ...
    return null;
  }
}
1
2
3
4
5
6
7
8
@Component("bStrategy")
public class BStrategy implements Strategy {
  @Override
  public Object verificate(StrategyBo strategyBo) {
    // ...
    return null;
  }
}
1
2
3
4
5
6
7
8
@Getter
@AllArgsConstructor
@NoArgsConstructor
public enum BizType {
  A("a", "aStrategy"),
  B("b", "bStrategy");

  private String features;

  private String service;
  
  public static BizType get(String features) {
    for(BizType o : values()) {
      if(o.features.equals(features)) {
        return o;
      }
    }
    return null;
  }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Component
public class StrategyFactory {

  @Autowired
  private Map<String, Strategy> strategyMap;

  public Strategy creator(String serviceName){
    return strategyMap.get(serviceName);
  }

}
1
2
3
4
5
6
7
8
9
10
11
@Service
public class TestService {

  @Autowired
  private StrategyFactory strategyFactory;

  public Object test(String features) {
    if (BizType.get(features) != null) {
      StrategyBo strategyBo = new StrategyBo();
      return strategyFactory.creator(BizType.get(features).getService()).verificate(strategyBo);
    }
    return null;
  }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

参考:
https://blog.csdn.net/kismet2399/article/details/83385197 (opens new window)