我有一个名为Human的类(在构造函数中接受name(string)和height(int))并且还需要创建一个这个类的供应商来创建一个对象,但是我想让对象的名字让& #39; s表示5-10个字符,高度应在110-250之间。是否有可能在Java中这样做?
答案 0 :(得分:0)
这是一种拒绝无效参数的方法
public class Human {
private final String name;
private final int height;
public Human(String name, int height) {
validateName(name);
validateHeight(height);
this.height = height;
this.name = name;
}
private void validateName(String name) {
if(name==null || name.length()<5 || name.length()>10)
throw new IllegalArgumentException("Name should be between 5-10 chars long but "+name);
}
private void validateHeight(int height) {
if(height<110 || height>250)
throw new IllegalArgumentException("Height should be between 110-250 but "+height);
}
}
请注意,这是RuntimeException
,变体包括抛出已检查的异常,并让客户端代码有变通方法。或者,可能有一个静态工厂方法,如果无效,则返回InvalidHuman对象。
<强>更新强>
好的,我想你想要这样的东西
public class HumanProvider {
private static final Random r = new Random();
private static String vowels = "aeiou";
private static String cons = "bcdfghjklmnpqrstvwxyz";
private static String[] patterns = "cvc vc cv cvvc vcc".split(" ");
private HumanProvider() {
} // don't instantiate
public static Human createRandom() {
String name;
do {
name = getRandomString();
} while (name.length() < 5 || name.length() > 10);
int height = r.nextInt(251 - 110) + 110;
return new Human(name, height);
}
private static String getRandomString() {
int numSyllabels = r.nextInt(5) + 1;
StringBuilder name = new StringBuilder();
for (int i = 0; i < numSyllabels; i++) {
String pattern = patterns[r.nextInt(patterns.length)];
for (char c : pattern.toCharArray()) {
name.append(randomChar((c == 'c') ? cons : vowels));
}
}
return name.toString();
}
private static char randomChar(String list) {
return list.charAt(r.nextInt(list.length()));
}
}
答案 1 :(得分:-1)
构造函数不能直接返回null,但您可以使用称为工厂方法的东西。工厂方法看起来像这样:
public static Human createHuman(String name, int height)
{
if (height < 110 || height > 250)
return null;
if (name == null || name.length() < 5 || name.length() > 10)
return null;
else
return new Human(name, height);
}
private Human (String name, int height) // note that this is private
{
this.name = name;
this.height = height;
}
您可以这样称呼它:
Human.createHuman("Steve", 117);
(或者在你的情况下,也许是这样:)
Supplier<Human> i = ()-> {return Human.createHuman(someName, someHeight)};