Springboot 策略模式的实现

Springboot 策略模式模板

接口

1
2
3
public interface Strategy {
	int action();
}

实现类

1
2
3
4
5
6
7
@Component
public class Strategy1 implements Strategy {
	@Override
	public int action() {
		return 1;
	}
}

上下文

@Autowired 可以注入Map或List, List存放全部实例对象,map的key是注入时的名。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
@Component
public class StrategyContext {
	private final Map<String, Strategy> map = new ConcurrentHashMap<>();
	@Autowired
	public void stragegyInteface(Map<String, Strategy> strategyMap) {
		strategyMap.forEach(this.map::put);
		System.out.println(this.map);
	}
	
	@Autowired
	public void stragegyInteface2(List<Strategy> strategyList) {
		strategyList.forEach(System.out.println);
	}
	
	public Strategy strategySelect(String mode) {
		return this.strategyMap.get(mode);	
	}
}

第二种方式参考https://liuyanzhao.com/1299032192516755457.html