I consider writing ZipCodeChecker interface like this:
public interface ZipCodeChecker {
public Pattern getFormatPattern();
public boolean isFormatValid(String zipCode);
}
And for each country zip code format I would make implementations like below (but this regex patterns is many so I hesitete if it wasn't better to have rather some hashmap and only one implementation)
public class USZipCodeChecker implements ZipCodeChecker {
public Pattern getFormatPattern( return countryspecificPattern; );
@Override
public boolean isFormatValid(String zipCode) {
return false;
}
}
And I would like to have CountryZipCodeValidator like this one:
public class CountryZipCodeValidator implements ConstraintValidator<CountryZipCode, Address> {
@Inject
private ZipCodeChecker checker;
@Override
public void initialize(CountryZipCode constraintAnnotation) {
}
@Override
public boolean isValid(Address value, ConstraintValidatorContext context) {
if(value.getZipCode() == null)
return true;
// value.getCountry() <-- based on this select @Inject checker implementation? but How????????
return checker.isFormatValid(value.getZipCode());
}
}
** In the place i commented I would like to get country name and based on this name to configure injected ZipCodeChecker in such way it will check zip code against given country specific format ***
I consider 3 approches:
-
Making ZipCodeChecker interface, many (50-100) ZipCodeCheckerImplementations, making producer which will @Produces ZipCodeChecker specific implementation based on condition of current country in validator where this implementation will be injected... I suppose I should use rather ** @Inject Instance checker** to dynamically load this country specific checker implementation
-
Make only one ZipCodeChacker implementation rather interface + many implementation... and @Inject this single ZipCodeChecker implementation pass to the method checker.isFormatValid(value.getZipCode(), value.getCountry())* and in ZipCodeChecker there will be some HashMap with Regex patterns and I get suitable regex pattern based on this country
-
Make some ZipCodeCheckerProvider and this will be @Inject-ed and in isValid() method do something like this provider.getChecker(value.getCountry) and this will return ZipCodeChecker country specific implementation like USZipCodeChecker.
-
Or maybe doesn't use CDI just add HashMap with zip code patterns and do all this matching in CountryZipCodeValidator, not using @Inject at all. Is is possible to place this regex strings in external resource like strings.xml (in android) and get it like Resources.getString("country-name");
Aucun commentaire:
Enregistrer un commentaire