I have a very simple factory which takes an Enum as one of its parameters to determine the type of object that should be created, and a other parameter that's common to all the objects being created.
As I'm adding more types for the factory to create my object constructor's parameters are starting to differ, eg:
public class someFactory {
public someFactory() {
}
public SomeObject newObject(Type type, Object data) {
return this.newObject(type, data, "");
}
public SomeObject newObject(Type type, Object data, Object stringOrObject) {
SomeObject someObject = null;
if (type != null) {
switch(type) {
case CREATE:
someObject = new CreateObject(data);
break;
case DELETE:
someObject = new DeleteObject(data, (String)stringOrObject);
break;
case EDIT:
someObject = new EditObject(data, (Object)stringOrObject);
break;
default:
break;
}
}
return someObject;
}
}
Should I not be using a factory and just instantiate the the different types with the right arguments or can the above be improved somehow to make it more flexible?
The standard Java thing to do is to add a method to the enum.
public enum Type {
CREATE() {
public SomeObject create(Object data, Object stringOrObject) {
return new CreateObject(data);
}
},
[...];
public SomeObject create(Object data) {
return create(data, "");
}
public abstract SomeObject create(Object data, Object stringOrObject);
}
As @Stas Kurilin points out, if you can avoid the enum and just call static creation methods of appropriate names and parameters, then you solve many problems.
(A few other random points: It's generally better to throw an exception than accept a null
or unknown value. Try to use strong typing rather than Object
. Stick with the Java coding conventions, such as capitalised type names.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With