Search code examples
design-patternsrequestresponse

Design pattern for similar request response


i need to design a service that consumes a request and produces a response. In terms of structure, I want the response to essentially echo the request AND also include a status.

e.g.

Request:

class Request {
String x;
String y;
}

class Response {
String x;
Status x_s;
String y;
Status y_s;
}

Is anyone aware of any patterns that describe this? One solution could be to use the same object to represent the request and response, in addiiotn with an object that encapsulates the value and status e.g.

class Attr {
 Status status;
 String value;
}

class RequestResponse {
Attr x;
Attr y;
}
  • This feels a bit clumsy though. E.g. the RequestResponse.attr.status would only be applicable to a response.
  • Note, in terms of the impl / usage fo this, with respect to the structure of the request / response is the same, the content will actually differ. I am attempting to implement a language translation service.

Thanks.


Solution

  • Why not

    public class Response {
        private Request request; // Has-a relationship
        private Status x_s;
        private Status y_s;
    }
    

    In addition to any design merits, this also has the added benefit that you "reuse" the memory already allocated for the request. It also lets you make use of functionality defined in the Request class when generating/handling the response, as in Request.getRequestType() or similar.

    Another solution is to have Response inherit from request (is-a relationship), but the compositional approach is usually better