0

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?

1
  • 2
    Can you paste some concrete code to demonstrate? Commented Aug 26, 2012 at 19:16

2 Answers 2

1

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).

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.