I have a Factory
class giving me handlers of DTO
objects. I made
my Factory
non instantiable.
public class CommonAdapterFactory {
// non instantiable
private CommonAdapterFactory() { }
}
Now I was wondering if there is a general rule about how to make getInstance
method signature.. I've found several ways, but most commons are this ones:
Use Class
I won't need to update an enum
or know String
values previously, but AFAIK no switch
is possible:
public static CommonAdapter getInstance(Class adapter) throws Exception {
if (adapter.equals(String.class))
return new StringAdapter();
throw new Exception("Parsed AdapterSelector is not compatible with AdapterFactory");
}
Use String
.
Allowing me to switch
but using and mantaining hardcoded constants (¿maybe in a different class?)
private static final String STRING = "String";
public static CommonAdapter getInstance(String adapter) throws Exception {
switch (adapter) {
case STRING:
return new StringAdapter();
default:
throw new Exception("Parsed AdapterSelector is not compatible with AdapterFactory");
}
}
Use enum
Similar to String
but IMHO maybe a cleaner way and not hardcoding any values.
public enum CommonAdapterSelector {
STRING,
OTHER;
}
// use enum (switch possible)
public static CommonAdapter getInstance(CommonAdapterSelector adapter) throws Exception {
switch (adapter) {
case STRING:
return new StringAdapter();
default:
throw new Exception("Parsed AdapterSelector is not compatible with AdapterFactory");
}
}
- Is there a standard?
- Some of this implementations can affect performance?
- Wich one is easier to mantain when more than 50 adapters can be created?
Aucun commentaire:
Enregistrer un commentaire