web层返回结果参数封装

1.定义一个枚举类,如下所示:

public enum ResultEnum {
    SUCCESS(0,"成功"),
    ERROR(1,"失败"),
    FAIL(-1,"未知错误");

    private int code;
    private String msg;

    ResultEnum(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

2.定义返回结果参数类,如下所示

public class ResponseParam implements Serializable {

    /**
     * 返回数据
     */
    private Map data = new HashMap<>();

    private int code;

    private String msg;

    public static ResponseParam SUCCESS(){
       return new ResponseParam(ResultEnum.SUCCESS);
    }

    public static ResponseParam ERROR(){
        return new ResponseParam(ResultEnum.ERROR);
    }

    public static ResponseParam FAIL(){
        return new ResponseParam(ResultEnum.FAIL);
    }

    private ResponseParam() {
    }

    private ResponseParam(ResultEnum resultEnum) {
       this.code = resultEnum.getCode();
       this.msg = resultEnum.getMsg();
    }

    private ResponseParam(int code, String msg,Map data) {
        this.data = data;
        this.code = code;
        this.msg = msg;
    }

    public static ResponseParam build(int code, String msg,Map data){
        return ResponseParam.ResponseParamBuilderHandler.build(code,msg,data);
    }

    public  ResponseParam addData(String key, T t){
        data.put(key,t);
        return this;
    }

    /**
     * 采用静态内部类实现单例模式创建对象
     */

    private static class ResponseParamBuilderHandler{
      private  static ResponseParam responseParam = new ResponseParam<>();
        public static ResponseParam build(int code,String msg,Map data){
            responseParam.setCode(code);
            responseParam.setMsg(msg);
            responseParam.setData(data);
            return  responseParam;
        }
    }

    public Map getData() {
        return data;
    }

    public void setData(Map data) {
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

3.测试

  @GetMapping("/pmc/sms/createTask")
    public ResponseParam createTask(){
        //smsCenterTaskSender.createTaskAndSender();
        Map map = new HashMap<>();
        map.put("1","1111");
        map.put("23","234");
        ResponseParam obj1 = ResponseParam.build(-2,"错误信息",map);
        ResponseParam obj2 = ResponseParam.build(-3,"错误信息2",map);
        if(obj1 == obj2){
            System.out.println("同一个实例对象");
        }
        return ResponseParam.build(-2,"错误信息",map);
    }

结果打印“同一个实例对象”

你可能感兴趣的:(web应用层)