Java – use factory pattern for classes with different parameters

I have a very simple factory that takes enumeration as one of its parameters to determine the type of object that should be created and another parameter common to all objects being created

When I add more types to the factory to create my object, the parameters of the constructor start to be different, for example:

Should I not use factories, just instantiate different types with the correct parameters, or can I improve it in some way to make it more flexible?

Solution

What standard Java does is add a method to an enumeration@ H_ 419_ 4@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 pointed out, if you can avoid enumeration and just call the appropriate name and parameters of the statically created method, you can solve many problems

(several other random points: throwing an exception is usually better than accepting null or unknown values. Try to use strong types instead of objects, and abide by java coding conventions, such as uppercase type names)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>