gpt4 book ai didi

Java 类设计 - 太多的 if 条件

转载 作者:搜寻专家 更新时间:2023-11-01 02:49:55 24 4
gpt4 key购买 nike

我的代码片段如下:

public void execute(Parameters params) {
Long requestType = params.getRequestType();
// Based on the requestType the name of the project would be different
getName(requestType);
// Same as above
getDescription(requestType)
// Project here is a collection of different requests
Long projectId = createProject(name, description)
RequestContents requestContents = params.getRequestContents();
for(RequestContent requestcontent : requestcontents) {
Long requestId = createRequest(name, description, projectId);
updateRequest(requestId, requestContent1);
}
// Based on the requestType, mail content would differ
String mailContent = getMailContent(requestType, projectId)
sendMail(mailContent);
}

函数 sendMailcreateProjectcreateRequest 的输出取决于 requestType,因此这些函数将最终有多个 if-else 条件。为此类建模以避免这种情况的正确方法是什么?

最佳答案

一种方法是创建一个抽象类 AbstractRequest 具有抽象方法 sendMailcreateProject 等,然后有几个具体的子类 RequestType1 RequestType2 等每个都有不同的 sendMail 等实现。我猜他们称之为策略模式。

关于Java 类设计 - 太多的 if 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13220798/

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