Background
Since I don't have a java background I'm struggling to create a factory object that returns implementations of a specific interface. Something similar to this...
Factory.create();
where create
should return an interface. Obviously, create
needs to know what I'm trying to "create". It could be by passing in a enum
so that create
can switch through all values of the enum
and decide what to create/return...I don't know exactly what's the best way to go about this.
Problem
The main problem I'm trying to solve is to provide an implementation-agnostic solution where consumers of this "factory framework" don't need to know anything about the implementation details. This allows me to change implementation classes and even swap out concrete implementations without having to re-factor an entire application or system.
What I currently have
I have the following interface in place
public interface EntityValidator<T> {
public boolean isValid(T t);
public List<String> getErrors();
}
and so far a couple of implementations that look like the class below...
public class Foo implements EntityValidator<EntityA> {
private List<String> errors;
public boolean isValid(EntityA a){
///implementation details
}
public List<String> getErrors(){
return errors;
}
}
the actual example is a fair bit more complex since there's an abstract class involved but that's out of the scope of this question. And finally the factory object, which is where I'm stuck at the moment
public final class EntityValidatorFactory {
public static <T> EntityValidator<T> create(MyEnum value){
if(value == VALUE_X){
//THIS IS WHERE I'm stuck
}
}
}
I can't seem to find the way to return out of the if
statement (which could be a switch
BTW)
Question
Is there a way to return a generic interface from a concrete class that implements it without having to manually cast it to that interface?
Any solution would be appreciated as long as it doesn't involve change the consuming code when I change or swap implementation classes.
Aucun commentaire:
Enregistrer un commentaire