gpt4 book ai didi

带有可选字段的 Java 对象

转载 作者:行者123 更新时间:2023-11-29 05:02:50 25 4
gpt4 key购买 nike

我有一个场景,请看

句子可以是:

String Subject + String Verb + String Object

String Subject + String Verb + String Adverb+ String Object

String Subject + String Verb + String Adjective+ String Object

String Subject + String Verb

我想创建一个 Sentence 类对象。

  Sentence s = new Sentence();
s.setSubject();
...

现在,我可以保留 Sentence 类中的所有字段,但我想确保没有字段必须为空。 我想从我在我创建对象的地方初始化的字段创建任何类型的句子。

eg: 
Sentence s = new Sentence();
s.setSubject();
s.setVerb();
s.setObject();
s.getValue(); // will return sentence value as S+V+O as I have set SVO

Sentence s = new Sentence();
s.setSubject();
s.setVerb();
s.getValue(); // will return sentence value as S+V as I have set SV

等等...我可以在 java 中做这样的事情吗?

基本上,我想避免未初始化的字段和空指针。

编辑

请注意,如果我将字段留空,即 ""或 null ,则形成的句子将类似于

“我没有上学。”或(动词为 null)。

“我正在学校”(动词是)。

所以,请在回答之前考虑这种情况。

最佳答案

我更喜欢使用构建器模式,让最终用户更清楚地使用并避免错误

    Public class Sentence {

private String subject;
private String verb;
private String adjective;
private String object;

//package private to ensure no one can call it outside package, canbe made pvt as well
Sentence(String subject, String verb, String adjective, String object) {
this.subject = subject;
this.verb = verb;
this.adjective = adjective;
this.object = object;
}

public static class SentenceBuilder{
private String subject;
private String verb;
private String adjective;
private String object;

private static final String EMPTY = "";

private String sanitizeInput(String input){
if (input==null){
return EMPTY;
}
return input;
}

private String validateInput(String input){
if(input==null || input.isEmpty()){
throw new IllegalArgumentException("cant be null or empty");
}
return input;
}

public SentenceBuilder(String subject, String verb) {
this.subject = validateInput(subject);
this.verb = validateInput(verb);
}

public SentenceBuilder adjective(String adjective){
this.adjective = sanitizeInput(adjective);
return this;
}

public SentenceBuilder object(String object){
this.object = sanitizeInput(object);
return this;
}

public Sentence build(){
return new Sentence(subject,verb,adjective,object);
}
}

public static void main(String[] args) {
//sample usage
Sentence sentence = new SentenceBuilder("subject","verb")
.adjective("adjective")
.object("object")
.build();
}
}

关于带有可选字段的 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31480109/

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