Java设计模式之策略模式

使用FeignClient注册的服务,虽然可以通过@Autowired实例化,但是实际注册使用的并非类名首字母小写,而是使用了代理,所以不能通过applicationContext.getBean()获取实例

一、接口

public interface ProcessInterface {
	//此方法用来注册一些不能通过spring上下文获取的实例,比如:FeignClient
    ProcessInterface register(Object... services);

     T getBean(Class clazz);

     T getVal(String key, Class clazz);

    ResponseBase process(ProcessReq processReq);
}

二、抽象类

public abstract class AbstractProcess implements ProcessInterface {

    private final Map localContext = new HashMap<>();

    public static ApplicationContext applicationContext;
	//此方法在springboot项目启动入口调用,或者是springMvc的话也可以自行实例化
    public static void setApplicationContext(ApplicationContext applicationContext){

        AbstractProcess.applicationContext = applicationContext;
    }
	//注册一些不能通过spring上下文直接获取的service或者其他参数
    @Override
    public ProcessInterface register(Object... services) {

        for(int i=0; i T getBean(Class clazz) {

        Object object = localContext.get(clazz.getName());
        try {

            T bean = clazz.cast(object);

            return bean;
        }catch (Exception e){

            e.printStackTrace();
        }
        return null;
    }
	//根据注册名获取注册进来的特定值
    @Override
    public  T getVal(String key, Class clazz) {

        Object object = localContext.get(key);
        try {

            T bean = clazz.cast(object);

            return bean;
        }catch (Exception e){

            e.printStackTrace();
        }
        return null;
    }
}

三、默认处理类

public class DefaultProcess extends AbstractProcess {

    @Override
    public ResponseBase process(ProcessReq processReq) {
        return ResponseBase.succeeded();
    }

}

四、指挥器

public class Director {

    private static final Map PROCESS_MAP = new HashMap<>();
	//注册处理器
    public static ProcessInterface register(int code, ProcessInterface process){

        ProcessInterface put = PROCESS_MAP.put(code, process);

        return put;
    }
	//根据code获取特定处理器
    public static ProcessInterface get(int code){

        ProcessInterface process = PROCESS_MAP.get(code);
        if (null != process){

            return process;
        }
        return new DefaultProcess();
    }

    static {
		
        register(code, new *Process());
    }

}

五、调用方式

ProcessInterface process = Director.get(code).register(*Service.class.getName(), *Service, "paramkey", paramval);

ResponseBase resp = process.process(processReq);

你可能感兴趣的:(Java,Design,Patterns)