I have an abstract class called Validator:
public abstract class Validator<T> where T : IValidatable
{
public abstract bool Validate(T input);
}
And I have a few concrete implementations. One is AccountValidator:
public class AccountCreateValidator : Validator<IAccount>
{
public override bool Validate(IAccount input)
{
//some validation
}
}
Another would be LoginValidator:
public class LoginValidator : Validator<IAccount>
{
public override bool Validate(IAccount input)
{
//some different validation
}
}
I now want to create a factory to return the an instance of a validator implementation. Something like:
public static class ValidatorFactory
{
public static Validator GetValidator(ValidationType validationType)
{
switch (validationType)
{
case ValidationType.AccountCreate:
return new AccountCreateValidator();
}
}
}
I'd then like to do call it like
Validator myValidator = ValidatorFactory.GetValidator(ValidationType.AccountCreate);
However it doesn't like the return new AccountCreateValidator() line, or the fact I'm declaring myValidator as Validator and not Validator<SomeType>
.
Any help would be appreciated.
It seems that you are using the factory to translate an enum argument into a concrete validation implementation. But I would imagine that although the caller does not know or care about the concrete type of the validator, it presumably does know the type it wishes it to validate. That should mean that it is reasonable to make the GetValidator method a generic method:
public static Validator<TypeToValidate> GetValidator<TypeToValidate>(ValidationType validationType) where TypeToValidate : IValidatable
Then calling code would look like this:
Validator<IAccount> validator = ValidatorFactory.GetValidator<IAccount>(ValidationType.AccountCreate
)