我希望一个类检查输入是否有效,并且所有有效的输入都记录在文本文件中。
因此,在构造中,它会读取文本文件并将所有有效输入放入 HashSet 中。然后我static
函数来接收输入并检查输入是否在 HashSet 中。
代码结构如下所示:
public class Validator {
HashSet validInputs;
public Validator() {
//read in
}
public static boolean validate(String in) {
//check and return
}
}
然后在其他类中,我需要使用该类来验证字符串Validator
。代码是这样的:
...
String a = XXX;
boolean valid = Validator.validate(a);
...
我还没有测试过代码,但我有两个问题:
- 行得通吗?是否读入了有效的输入文本文件?
- 类何时读取文本文件?
- 每次调用函数
validate()
时,Validator
都会读取文本文件吗?
不行得通吗?是否读入了有效的输入文本文件?
,那行不通。
您的方法应该是实例方法,以便它可以访问其他实例成员。
public boolean validate(String in) {
//check and return
}
类何时读取文本文件?
您必须先构造该类,然后才能使用它。在构造函数中读取文本文件。
每次调用函数 validate() 时,验证器都会读取文本文件吗?
不。调用 new Validator()
时调用构造函数。
您可以使用单例和非静态validate
-方法:
public class Validator {
private static Validator instance = null;
/**
* Do not use new Validator; use Validator.getInstance() instead.
*/
private Validator() {
// read in
}
public static Validator getInstance() {
if(instance == null) {
instance = new Validatorr();
}
return instance;
}
public boolean validate(String str) {
// check and return
}
}
在您需要validate
某些东西的任何地方,请使用:
Validator.getInstance().validate()
注意:以这种方式实现的单例模式的副作用是,如果不使用验证程序,则不会创建验证程序,也不会读取in
。 这可能是您想要的,也可能不是您想要的。
不会。 validInputs
将绑定到Validator
实例,并且无法从静态方法中引用它。你需要的是一个静态块:
public final class Validator {
private static HashSet validInputs;
private Validator() {}
static {
//read in
}
public static boolean validate(String in) {
//check and return
}
}
如果这样做:
When will the class read in the text file? - When the class is loaded by the Class loader.
Will Validator read the text file every time I call the function validate()? - No, only when the class is loaded.
不,在创建Validator
实例之前,您将无法访问validInputs
new Validator()
- 不会,您的文件在使用时不会被读入。
- 当您创建
Validator
的新实例时,将读取该文件。 - 不。只有当您有
new Validator()
时,才会读入它。
如果您希望能够以静态方式访问此方法,请考虑使用 Singleton
。