设计模式-工厂

使用场景

屏蔽内部复杂,符合迪米特法则(最少知道原则)

原理

根据标识(string,emum),创建相关对象(一组实现相同接口对象)

招式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

public class StrategyFactory<T, S extends Strategy<T>>
implements InitializingBean, ApplicationContextAware {

private final Class<S> strategyType;

private Map<T, S> strategyMap;

private ApplicationContext appContext;

/**
* 创建一个策略工厂
*
* @param strategyType 策略的类型
*/
public StrategyFactory(Class<S> strategyType) {
this.strategyType = strategyType;
}

/**
* 根据策略 id 获得对应的策略的 Bean
*
* @param id 策略 id
* @return 策略的 Bean
*/
public S getStrategy(T id) {
return strategyMap.get(id);
}

@Override
public void afterPropertiesSet() {
// 获取 Spring 容器中,所有 S 类型的 Bean
Collection<S> strategies = appContext.getBeansOfType(strategyType).values();

strategyMap = Maps.newHashMapWithExpectedSize(strategies.size());

// 将 所有 S 类型的 Bean 放入到 strategyMap 中
for (final S strategy : strategies) {
T id = strategy.getId();

strategyMap.put(id, strategy);
}
}

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
appContext = applicationContext;
}
}

参考

https://mp.weixin.qq.com/s?__biz=MzAxNDEwNjk5OQ==&mid=2650432631&idx=1&sn=fd90b80b2fe566b6f04a67fc18f156aa&chksm=8396ac6fb4e125799c6b2329fdb67727e1da3949a4c2f4a879e80f1d83591fcea2744b76f124&mpshare=1&scene=1&srcid=1130XXmPwschNyomtGkEQPvb&sharer_sharetime=1638251225567&sharer_shareid=21878bc7924c790b0c0f03ef06b36d15&key=e659f3596625ecf27da3dfe12c21b9d0ab6196d90c93ebd6ef0350cb39e85d5011980f9e404c8ecf9ce2e4ba183c8a94a82716f1099b5f0c8c3a4de3f07c4e40273037b1c31be2a76d1e0df599df7ec50ab616eb1ef6695785f2a86cb365c7faf4fe997e6766db9b15d6699660d287de1f345b09229df6149d0d55ad4833baf1&ascene=1&uin=OTM4NTY4MzU%3D&devicetype=Windows+10&version=62060844&lang=zh_CN&exportkey=AYClbodKvloqPXREo8WM3Kc%3D&pass_ticket=E2HAxmlxE49N%2BHNKlcaaoJaZhFVYW1ALfzpBQFpFc5eS5fsfcMcK3nX%2BMTgMxZGA&wx_header=0