patternjavaMinor
FactoryPattern without If-else construct
Viewed 0 times
constructwithoutfactorypatternelse
Problem
Someone asked me if I can create factory pattern in java without using If-else construct. So I come with the following. Please provide your inputs if this seems a good example for using factories.
public enum EnumButtonFactory {
RADIO(RadioButton.class),
SUBMIT(SubmitButton.class),
NORMAL(NormalButton.class);
private Class button;
EnumButtonFactory(Class b) {
this.button = b;
}
public Button get() {
try {
return button.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
}Solution
This is a good example for demonstrating that you can implement factory pattern without conditional statements. Of course, no piece of code is good for every imaginable requirement.
In real world cases factory pattern usually needed because some aspect of the object building is not trivial. One such case is when you do not have the concrete classes at compile time. e.g. when you are a library/framework developer and the user will have the concrete classes. In that case you would want to externalize the class names to the program configuration. This program requires that you have the
In real world cases factory pattern usually needed because some aspect of the object building is not trivial. One such case is when you do not have the concrete classes at compile time. e.g. when you are a library/framework developer and the user will have the concrete classes. In that case you would want to externalize the class names to the program configuration. This program requires that you have the
SubmitButton.class et al at compile time, and is dependent of those concrete classes.Context
StackExchange Code Review Q#21102, answer score: 5
Revisions (0)
No revisions yet.