Search code examples
javavalidationdesign-patternsxmlbeans

Which design pattern should be used in this use case?


I am working on app where I have to write custom validation on some xmlbean oject, basically to see so and so fields with proper values exist or not. Now those objects are generated from diff schema. I am using validation provided by xmlbeans against the schema but there are some more business validation needs to be done for these objects before it is being processed further. Can somebody suggest any design pattern for this use case?

Thanks


Solution

  • Define your own validator interface:

    interface Validator <T extends XmlBean> {
        boolean validate(T bean);
    }
    

    Implement it for each classyou are dealing with, you can provide a factory class to get the validator for each bean class by implementing the following interface:

    interface IValidatorFactory {
        public <T extends XmlBean> Validator<T> getValidator(Class<T> clazz);
    }
    
    class ValidatorFactory implements IValidatorFactory {
        private final Map<Class<? extends XmlBean>, Validator<? extends XmlBean>> map =
            new HashMap<Class<? extends XmlBean>, Validator<? extends XmlBean>>();
    
        @SuppressWarnings("unchecked")
        @Override
        public <T extends XmlBean> Validator<T> getValidator(Class<T> clazz) {
            return (Validator<T>)map.get(clazz);
        }
    
        public <T extends XmlBean> void registerValidator(Class<T> clazz, Validator<T> validator) {
            map.put(clazz, validator);
        }
    }