链式编程

例如返回结果封装的vo,可以因为方法返回的是自身,所以用的时候可以.set().set().set()

下面定义了一个vo类

public class R {

    private int code;
    private String msg;
    private Object result;

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public Object getResult() {
        return result;
    }


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

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

    public R setResult(Object result) {
        this.result = result;
        return this;
    }

    public R setResult(String key, Object value) {
        if (result == null) {
            JSONObject result = new JSONObject();
            result.put(key, value);
            this.result = result;
        }else{
            if (result instanceof JSONObject) {
                ((JSONObject)result).put(key, value);
            }
            if (result instanceof Map) {
                ((Map)result).put(key, value);
            }
        }
        return this;
    }

    /**
     * 封装成功方法
     */
    public static R ok(){
        return new R()
                .setCode(200)
                .setMsg("请求成功");
    }
    public static R ok(int code){
        return new R()
                .setCode(code)
                .setMsg("请求成功");
    }
    public static R ok(String msg){
        return new R()
                .setCode(200)
                .setMsg(msg);
    }
    public static R ok(int code,String msg){
        return new R()
                .setCode(code)
                .setMsg(msg);
    }
    public static R ok(Object data){
        return new R()
                .setCode(200)
                .setMsg("请求成功")
                .setResult(data);
    }

    /**
     *  封装失败的方法
     */
    public static R error(){
        return new R()
                .setCode(500)
                .setMsg("请求失败");
    }
    public static R error(int code){
        return new R()
                .setCode(code)
                .setMsg("请求失败");
    }
    public static R error(String msg){
        return new R()
                .setCode(500)
                .setMsg(msg);
    }
    public static R error(int code,String msg){
        return new R()
                .setCode(code)
                .setMsg(msg);
    }
    public static R error(Object data){
        return new R()
                .setCode(500)
                .setMsg("请求失败")
                .setResult(data);
    }

    /**
     * R转json的方法
     */
    public String toJsonString(R r){
        return JSONObject.toJSONString(r);
    }
    /**
     * 重写toString
     */
    @Override
    public String toString() {
        return toJsonString(this);
    }
}

 

上一篇:InnoDB的锁机制浅析(一)—基本概念/兼容矩阵


下一篇:python+selenium+Robot