适配器工厂
阿昌 Java小菜鸡

适配器工厂

  • 使用背景

    根据不同的类型,会有不同的业务逻辑

  • 举例

    判断一个字段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
    39
    public 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
    13
    import org.springframework.core.annotation.AliasFor;
    import java.lang.annotation.*;

    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface Adapter {
    @AliasFor(attribute = "platform")
    String[] value() default {};

    @AliasFor(attribute = "value")
    String[] platform() default {};
    }
  • 使用举例

1
2
3
public interface CatTemplete {
void miao();
}
1
2
3
4
5
6
7
@Adapter("blackCat")
@Component
public class BlackCatTempleteImpl implements CatTemplete{
void miao(){
System.out.println("im black cat");
}
}
1
2
3
4
5
6
7
@Adapter("whiteCat")
@Component
public class whiteCatTempleteImpl implements CatTemplete{
void miao(){
System.out.println("im white cat");
}
}
1
2
3
4
public void test(){
CatTemplete catTemplete = AdapterFactory.getInstance(CatTemplete.class, "blackCat");
catTemplete.miao();
}
 请作者喝咖啡