直接上代码:
package common;
import com.alibaba.fastjson.JSON;
import java.io.Serializable;
/**
* 建造者模式:通用服务端返回报文设计
*/
public class ServerResult implements Serializable {
public static final String STATUS_SUCCESS = "200";
private String code;
private String msg;
private Object result;
public ServerResult(String code, String msg, Object result){
this.code = code;
this.msg = msg;
this.result = result;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
public static ServerResult error(String code, String msg) {
return getBuilder().setCode(code).setMsg(msg).build();
}
public static ServerResult error(String code, String msg, Object object) {
return getBuilder().setCode(code).setMsg(msg).setResult(object).build();
}
public static ServerResult ok(String msg) {
return getBuilder().setCode(STATUS_SUCCESS).setMsg(msg).build();
}
public static ServerResult ok(Object result) {
return getBuilder().setCode(STATUS_SUCCESS).setResult(result).build();
}
public static ServerResult ok(String msg, Object result){
return getBuilder().setCode(STATUS_SUCCESS).setMsg(msg).setResult(result).build();
}
public static ServerResult ok() {
return getBuilder().setCode(STATUS_SUCCESS).setMsg("").build();
}
public static Builder getBuilder(){
return new Builder();
}
public static class Builder {
private String code;
private String msg;
private Object result;
public Builder setCode(String code) {
this.code = code;
return this;
}
public Builder setMsg(String msg) {
this.msg = msg;
return this;
}
public Builder setResult(Object result) {
this.result = result;
return this;
}
public ServerResult build(){
System.out.println(code);
return new ServerResult(code, msg, result);
}
}
/**
* 使用示例
* @param args
*/
public static void main(String[] args) {
System.out.println(JSON.toJSONString(ServerResult.ok()));
System.out.println(JSON.toJSONString(ServerResult.error("10001","xx")));
}
}