gpt4 book ai didi

java - 使用几个 boolean 条件 java 改进代码

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:05:24 24 4
gpt4 key购买 nike

我有一个大问题要处理,我的代码太长且字符太多。我去掉了很多,使用方法和使用一些适当的设计模式......但它仍然太“拥挤”。

我从用户那里得到一个字符串,问题如下:

"How are you Josh?"
"Who is Josh's mother?"

我需要分析那个问题,以便查看它的内容并将答案发送给 System.out.print()。

所以一长串的“if/else if”开始了,例如

if (question.startsWith("How") && question.endsWith("Josh?"))
{
//do a lot of things here.

System.out.print(actualHealth);
}

else if (question.startsWith("Who") && question.endsWith("mother?"))
{
//do a lot of things here.

System.out.print(getParents().getMother());
}

*
*
* //Lot of "else if" here to recognize the question meaning.
*
*

else
{
System.out.print("question not recognized");
}

我将此类 AnswersFactory 称为设计模式“工厂模式”,因为问题是在另一个类中“提出”的。但我认为将其视为设计模式是一种错误的方式。

如何简化所有这些条件,即使它们似乎无法简化,或者至少使代码看起来更有条理?有好的设计模式可以遵循吗?

我的代码工作得很好,但看起来并不漂亮。我希望你能理解那种挫败感!

谢谢。

最佳答案

不确定为什么要根据关键字检查问题,它有一些缺点,如 HCBPshenanigans 提到的但是为了让它更灵活,我会做这样的事情:

所有问题处理程序的接口(interface)

public interface IQuestionHandler
{
bool CanHandle(string question);
void Handle(string question);
}

每个场景的具体类。每个类都会告诉它是否可以处理问题,并包含处理问题的逻辑:

public class HealthQuestionHandler : IQuestionHandler
{
public bool CanHandle(string question)
{
return question.StartsWith("How") && question.EndsWith("Josh?");
}

public void Handle(string question)
{
//Replace by actual processing
string healthStatus = "I'm fine";

Console.WriteLine(healthStatus);
}
}

public class MotherQuestionHandler : IQuestionHandler
{
public bool CanHandle(string question)
{
return question.StartsWith("Who") && question.EndsWith("mother?");
}

public void Handle(string question)
{
//Replace by actual processing
string mother = "...";

Console.WriteLine(mother);
}
}

最后是一个问题处理器来管理所有的处理器。它将在构造函数中注册所有可用的处理程序。当调用处理时,它会遍历所有可用的处理程序,一个一个地询问哪个可以处理该问题

public class QuestionHandlerProcessor
{
private List<IQuestionHandler> _handlers;

public QuestionHandlerProcessor()
{
//Register available handlers
_handlers = new List<IQuestionHandler>
{
new HealthQuestionHandler(),
new MotherQuestionHandler()
};
}

public void Process(string question)
{
foreach(var handler in _handlers)
{
if(handler.CanHandle(question))
{
handler.Handle(question);
return;
}
}

Console.WriteLine("Question not recognized");
}
}

用法:

QuestionHandlerProcessor processor = new QuestionHandlerProcessor();
processor.Process("How are you Josh?");
processor.Process("Who is Josh's mother?");

虽然我的答案是用C#,但是转换成Java应该不难。

关于java - 使用几个 boolean 条件 java 改进代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25090301/

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