I want a class to check if an input is valid, and all the valid input is record in a text file.
So in construction, it read in the text file and put all valid inputs into a HashSet. Then I have static function to receive an input and check if the input is in the HashSet.
Code structure is like following:
public class Validator {
HashSet validInputs;
public Validator() {
//read in
}
public static boolean validate(String in) {
//check and return
}
}
Then in other class, I need to use Validator class to validate strings. Code is like:
...
String a = XXX;
boolean valid = Validator.validate(a);
...
I haven’t tested the code, but I have two questions:
- Does it work? Is the valid input text file read in?
- When will the class read in the text file?
- Will
Validatorread the text file every time I call the functionvalidate()?
You could use a singleton and a non-static
validate-method:Everywhere where you need to
validatesomething use:NOTE: A side effect of the singleton pattern implemented this way is that if the Validator is not used, the Validator is not created and
inis not read. This may or may not be what you want.