适配器工厂

适配器工厂
使用背景
根据不同的类型,会有不同的业务逻辑
举例
判断一个字段
shop
:TB/TM/JD/FXG/KS/…..会调用不同商家api进行不同的处理逻辑
技术点
org.springframework.core.annotation.AnnotationUtils
+SpringIOC
+注解
使用举例
- 适配器工厂
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
39public class AdapterFactory {
//一个会多线程访问的缓存Map
private static final ConcurrentMap<String, Object> INSTANCE_MAP = new ConcurrentHashMap<>();
//获取IOC容器中对应标记@Adapter注解的Bean
public static <T> T getInstance(Class<T> type, String source) {
Map<String, T> maps = ApplicationContextUtil.getApplicationContext().getBeansOfType(type);
if (maps.isEmpty()) {
throw new AdapterException("找不到对应的实例type=" + type.getName() + ";source=" + source);
}
String key = source + "_" + type.getName();
Object t = INSTANCE_MAP.get(key);
if (t != null) {
return type.cast(t);
}
for (T obj : maps.values()) {
Adapter adapter = AnnotationUtils.findAnnotation(obj.getClass(), Adapter.class);
if (adapter != null && contains(adapter.value(), source)) {
T instance = type.cast(obj);
INSTANCE_MAP.putIfAbsent(key, instance);
return instance;
}
}
throw new AdapterException("找不到对应的实例type=" + type.getName() + ";source=" + source);
}
private static boolean contains(String[] sourceArr, String source) {
if (sourceArr == null || StringUtils.isEmpty(source)) {
return false;
}
for (String s : sourceArr) {
if (source.equals(s)) {
return true;
}
}
return false;
}
}- @Adapter注解
1
2
3
4
5
6
7
8
9
10
11
12
13import org.springframework.core.annotation.AliasFor;
import java.lang.annotation.*;
public Adapter {
String[] value() default {};
String[] platform() default {};
}使用举例
1 | public interface CatTemplete { |
1 |
|
1 |
|
1 | public void test(){ |