我现在的问题是我需要将某项业务,通过封装为get请求,供其他用户来调用,这样就有一个问题,我应该如何设计这个请求的返回结果的格式?因为有多种类型的返回结果,所以将每种返回结果存放到不同的字段,我现在想到的是给一个flag字段,但是需要调用者根据flag来判断展示结果中的哪个字段,不知道有没有什么更加优雅的实现方式。
PHP中文网2017-04-17 18:03:05
Use generics to define a return object
public class ServiceResult<T> {
private String msg="";//消息说明
private int resultCode=0;//结果消息代码
private T data;//返回的数据字段
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getResultCode() {
return resultCode;
}
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
/**
*
* 一个service对象
*/
public class MyServices {
public List<User> getUserList(){
return new ArrayList<User>();
}
public User getUserByID(Long userId){
return new User();
}
}
/**
* user
*/
class User{
private String name;
private Long id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
/**
* request调用
*/
public class UserRequestObject {
public void doReuest(String requestType){
MyServices someMyServices=new MyServices();
if(requestType.equals("userList")){
ServiceResult<List<User>> result=new ServiceResult<List<User>>();
result.setData(someMyServices.getUserList());
}else if (requestType.equals("user")){
ServiceResult<User> result=new ServiceResult<User>();
result.setData(someMyServices.getUserByID(0L));
}else{
ServiceResult<Void> result=new ServiceResult<Void>();
result.setData(null);
}
//数据转成JSON格式,返回给调用者
}
}
PHPz2017-04-17 18:03:05
Generally speaking, you can define a return format as follows. resultCode
定义了多种返回类型,比如除了resultCode
为0
其他均为错,且errorMsg
有具体说明,正常业务的返回对象由result
描述,在里面我们可以定义正常逻辑的多种返回类型,比如可以用resultType
表示不同的类型,多个字段分别包装不同类型结果,如果差别不大,不一定需要多个字段,一个字段即可(里面的字段内容可以为null
).
{
String resultCode;
String errorMsg;
Object result;
}
result描述:
{
String resultType;
ResultForm resultForm;
}
PHP中文网2017-04-17 18:03:05
If it is http, you can use the header to pass the format of the request, and then the interface determines the format of the corresponding response. Non-HTTP is also similar. The caller provides the required format or field, and the server can provide different results according to the identification.