适合任务的设计模式

时间:2018-10-12 08:02:52

标签: java spring design-patterns strategy-pattern

数据库包含以下类型的行: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的正确名称?

1 个答案:

答案 0 :(得分:-1)

让我们这样考虑:

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;
}

也许这种方法对您而言会更好。好吧,让我来。