Reputation: 1232
For a small system I create related objects (that inherits from parent class) using factory method so that I can create object dynamically without specifying the type of object. I have to create another objects that don't have subclasses and that objects are an instance of user class. To correctly understand the factory method pattern I don't have to create a factory method for the last class right?
Upvotes: 0
Views: 1130
Reputation: 1774
I think if your existing Factory is serving the related objects then you might want to create another Factory. I think its fine even if your factory creates only one type of object.
Upvotes: 0
Reputation: 200138
The Factory pattern is not only about type flexibility. For example, Java has Integer.valueOf(int)
even though it already has new Integer(int)
. The factory variant allows caching: each call of Integer.valueOf(1)
will return the same instance. This works for all immutable objects.
Yet another, very important point of consideration is object initialization: there are some initialization patterns that are just not safe to accomplish while the object is under construction. For example, calling any overridable methods. These cases are also elegantly solved by the Factory pattern.
I personally would argue for a third benefit, but this may be controversial to some: I much prefer to write code without new
. For example, instead of new OidableBinding(vb)
I like to write oidableBinding(vb)
. This is made possible by static imports. So a side note: don't name your factory method getInstance
or similar. Name it similar to the type name so the method looks nice when statically imported (and doesn't create name clashes with other blandly named factory methods).
Upvotes: 1