数据库包含以下类型的行:TYPE1, TYPE2, TYP3, TYPEN

当用户向我的服务发送请求并等待响应时,我将执行以下操作:

1)呼叫responseService进行响应:

@Override
public GetResponseResponse getResponse(GetResponseRequest request)
       return responseService.getResponse(request);
}


2)在responseService中准备响应:

@Override
@Transactional
public GetResponseResponse getResponse(GetResponseRequest request) {

    //get data from DB
    SmevMessage smevMessage = smevMessageService.findOneFinished(request.getP1(), request.getP2());

    //validate

    //create general response for all TYPES of response
     GetResponseResponse getResponseResponse = new GetResponseResponse();

    //get Builder for concrete resonse part
    UnpResponseBuilder unpResponseBuilder = unpResponseBuilderContext.getResponseBuilder(smevMessage.getRequestType());
    Element element = unpResponseBuilder.createResponse(smevMessage);

    //set part to general response
    getResponseResponse.setAny(element);

    return getResponseResponse;
}


我生成一般响应,但是每种响应都有每种类型的特定部分。我为此使用策略设计模式。

我对此接口有一些实现:

public interface UnpResponseBuilder {
    Element createResponse(SmevMessage smevMessage);
}


一个bean-上下文:

public interface UnpResponseBuilderContext {
    UnpResponseBuilder getResponseBuilder(SmevMessageType smevMessageType);

    void setBuilder(SmevMessageType smevMessageType, UnpResponseBuilder bean);
}


我的问题:为这项任务使用策略是否正确?还有其他可能吗?如果策略适合UnpResponseBuilderContextUnpResponseBuilder的正确名称?

最佳答案

让我们考虑一下这种方式:

public CreateResponseStrategy {
  public Element createResponse(SmevMessage smevMessage);
}

public FirstCreateResponseStrategy implements CreateResponseStrategy {
  public Element createResponse(SmevMessage smevMessage) {
  //logic
  }
}

public SecondCreateResponseStrategy implements CreateResponseStrategy {
  public Element createResponse(SmevMessage smevMessage) {
  //logic
  }
}


然后在您的responseService类中:

final ImmutableMap<String,CreateResponseStrategy> strategyMap = ImmutableMap.<String, CreateResponseStrategy>builder()
            .put("firstType", new FirstCreateResponseStrategy())
            .put("secondType",new SecondCreateResponseStrategy() )
            .build()

public GetResponseResponse getResponse(GetResponseRequest request) {

    //get data from DB
    SmevMessage smevMessage = smevMessageService.findOneFinished(request.getP1(), request.getP2());

    GetResponseResponse getResponseResponse = new GetResponseResponse();

    Element element = strategyMap.get(smevMessage.getRequestType()).createResponse(smevMessage); //additionaly check if element exists in map

    getResponseResponse.setAny(element);

    return getResponseResponse;
}


也许这种方法对您而言会更好。如果可以的话让我。

10-08 13:05