|
| 1 | +package strategy.controller; |
| 2 | + |
| 3 | +import jakarta.annotation.PostConstruct; |
| 4 | +import org.springframework.beans.factory.annotation.Autowired; |
| 5 | +import org.springframework.web.bind.annotation.GetMapping; |
| 6 | +import org.springframework.web.bind.annotation.PathVariable; |
| 7 | +import org.springframework.web.bind.annotation.RestController; |
| 8 | +import strategy.annotation.SupportAttackType; |
| 9 | +import strategy.enums.AttackType; |
| 10 | +import strategy.service.AttackService; |
| 11 | +import strategy.service.DefaultAttack; |
| 12 | + |
| 13 | +import java.util.List; |
| 14 | +import java.util.Map; |
| 15 | +import java.util.function.Function; |
| 16 | +import java.util.stream.Collectors; |
| 17 | + |
| 18 | +@RestController |
| 19 | +public class AttackController { |
| 20 | + private Map<AttackType, AttackService> attackServiceMap; |
| 21 | + |
| 22 | + @Autowired |
| 23 | + private DefaultAttack defaultAttackService; |
| 24 | + |
| 25 | +// @Autowired |
| 26 | +// private List<AttackService> attackServices; |
| 27 | + |
| 28 | + @GetMapping("/attack/{type}") |
| 29 | + public String attack(@PathVariable(value = "type") int type) { |
| 30 | + AttackType attackType = AttackType.typeOf(type); |
| 31 | + AttackService attackService = attackServiceMap.getOrDefault(attackType, defaultAttackService); |
| 32 | + return attackService.attack(); |
| 33 | + } |
| 34 | + |
| 35 | + @Autowired |
| 36 | + private void setAttackServiceMap(List<AttackService> attackServiceList) { |
| 37 | + this.attackServiceMap = attackServiceList.stream() |
| 38 | + .filter(attackService -> attackService.getClass().isAnnotationPresent(SupportAttackType.class)) |
| 39 | + .collect(Collectors.toMap(AttackService::getAttackTypeByService, Function.identity())); |
| 40 | + if (this.attackServiceMap.size() != AttackType.values().length) { |
| 41 | + throw new IllegalArgumentException("some attack types are not supported"); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + //The following code completes the same task as setAttackServiceMap(List) |
| 46 | + /*@PostConstruct |
| 47 | + private void initAttackServiceMap() { |
| 48 | + this.attackServiceMap = attackServices.stream() |
| 49 | + .filter(attackService -> attackService.getClass().isAnnotationPresent(SupportAttackType.class)) |
| 50 | + .collect(Collectors.toMap(AttackService::getAttackTypeByService, Function.identity())); |
| 51 | + if (this.attackServiceMap.size() != AttackType.values().length) { |
| 52 | + throw new IllegalArgumentException("some attack types are not supported"); |
| 53 | + } |
| 54 | + }*/ |
| 55 | +} |
0 commit comments