我有一个类Response,其中包含HTTP响应,其HTTP状态代码如200或404以及其他一些内容,如视图名称和域对象.但是让我们关注状态代码.我可以使用单个类并将状态作为参数传递:
public class Response {
private int status;
public Response(int status) {
this.status = status;
}
}
// in a handler method:
return new Response(HttpStatus.OK);
Run Code Online (Sandbox Code Playgroud)
另一种方法是为每个状态代码创建一个新类(HTTP 1.1中的41个状态代码).像这样:
public class Ok extends Response {
public Ok() {
super(HttpStatus.OK);
}
}
// in a handler method:
return new Ok();
public class Created extends Response {
public Created() {
super(HttpStatus.CREATED);
}
}
// in a handler method:
return new Created();
Run Code Online (Sandbox Code Playgroud)
实际上,通常会有更多参数,例如视图名称和域对象,就像这样new Response(HttpStatus.OK, "customer", customer)各自new Ok("customer", customer).