gpt4 book ai didi

java - 为 Web 服务建模请求和响应对象的设计模式

转载 作者:IT老高 更新时间:2023-10-28 21:18:50 25 4
gpt4 key购买 nike

我有大约 7 个 REST Web 服务要实现。其中一些 Web 服务具有标准(相同)响应,而另一些具有不同响应。

这些 Web 服务的请求是不同的,但一些请求和一些响应具有相同的底层数据对象。

我不确定是否必须为每个 Web 服务构建单独的请求/响应类或重用一个标准的类。我想知道是否有一种设计模式可以为这些 Web 服务的请求对象和响应对象建模。

好的,假设 Account 和 Book 是我的 Web 服务将处理的两个其余资源。

class Account {
String username;
String id;
}


class Book {
String title;
String isbn;
}

所以我的网络服务看起来像这样:
MYAPI/CreateAccountandBook
MYAPI/Account/Create
MYAPI/Book/Create
MYAPI/Book/Update/{isbn}
MYAPI/Account/Update/{id}
MYAPI/Account/getInfo/{id}

等等。

现在 CreateAccountandBook request 将在有效负载中接受一个帐户对象和一个书籍列表。
也是 MYAPI/Account/getInfo/{id} 的响应对象有一个帐户对象和与该帐户关联的图书列表。但是响应对象还包括一个 statusCodeDescription .

现在我想为这些请求和响应对象创建类
以最好的方式。

好的开始。

我有两个抽象类 StandardRequestStandardResponse .

所有请求类都将扩展标准请求类并相应地进行自定义。
所有响应类都将扩展标准响应类并相应地进行自定义。

但是这些请求和响应可以彼此不同,但仍然重用相同的实体对象。

例如:
createAccountandBook请求对象如下所示:
class CreateAccountAndBookRequest {
Account account;
List<Book> books;
}

而对 getInfo 的响应网络服务是:
class GetInfoResponse {
Account account;
List<Book> books;
String statusCode;
String description;
}

所以请求和响应类之间存在重叠。我可以为每个 Web 服务创建两个(req/res)类。但是想知道是否有更好的方法来对这些类进行建模。

最佳答案

我也有类似的困境;我去了通用 方向,我喜欢结果;从那以后就没有回头。

如果我有一个 GetAccounts签名可能看起来像的 API 方法。

public final Response<Account[]> getAccounts()

自然地,相同的原则可以应用于请求。
public final Response<Account[]> rebalanceAccounts(Request<Account[]>) { ... }

在我看来;将单个实体与请求和响应分离会产生一个更整洁的域和对象图。

下面是这种通用响应对象可能是什么样子的示例。就我而言;我构建的服务器对所有请求都有一个通用的响应,以增强错误处理并降低域对象和响应对象之间的耦合。
public class Response<T> {

private static final String R_MSG_EMPTY = "";
private static final String R_CODE_OK = "OK";

private final String responseCode;
private final Date execDt;
private final String message;

private T response;

/**
* A Creates a new instance of Response
*
* @param code
* @param message
* @param execDt
*/
public Response(final String code, final String message, final Date execDt) {

this.execDt = execDt == null ? Calendar.getInstance().getTime() : execDt;
this.message = message == null ? Response.R_MSG_EMPTY : message;
this.responseCode = code == null ? Response.R_CODE_OK : code;
this.response = null;
}

/**
* @return the execDt
*/
public Date getExecDt() {

return this.execDt;
}

/**
* @return the message
*/
public String getMessage() {

return this.message;
}

/**
* @return the response
*/
public T getResponse() {

return this.response;
}

/**
* @return the responseCode
*/
public String getResponseCode() {

return this.responseCode;
}

/**
* sets the response object
*
* @param obj
* @return
*/
public Response<T> setResponse(final T obj) {

this.response = obj;
return this;
}
}

关于java - 为 Web 服务建模请求和响应对象的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26788608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com