Fresher Fresher - 1 year ago 109
Java Question

"Factory Method Design Pattern" in context of Java interfaces?

I am a beginner in Java and the book that I use to learn it seems to have cryptic examples and sentences that completely confuse me.

I understand what interfaces are and how/where to apply the concept in real world. But what are Factory Methods? The term "factory method" is ambiguous (JavaScript has a different meaning for that) so I am providing the snippet that the book has, in order to make my question clear. Here is the code:

interface Service {
void method1();
void method2();

interface ServiceFactory {
Service getService();

interface is just a normal interface.
interface looks like a normal interface but it is a "Factory Method". What's that? What does it solve and why I should use them?

Answer Source

A "factory method" is a method that constructs an object.

More specifically, the term usually refers to a static method that returns an instance of its declaring class (either a direct instance, or an instance of a subclass). In my experience, there are a few cases where that's particularly commonly done:

  • If you need to have multiple different constructors, using factory methods lets you give them appropriate names (whereas calls to different constructors can only be distinguished by the argument-types, which aren't always obvious at a glance).
  • If you need to have a few different implementations of a single abstract class that serves as the entry-point, the factory method can instantiate the appropriate subtype.
  • If you need any sort of caching logic or shared instances, the factory method can handle that, returning an already-existing instance if appropriate.
  • If you need to do some work with side effects, a factory method can be named in such a way that it's more clear what those side effects are.

So, your example doesn't really involve a "factory method" IMHO, but you can cheat a bit and describe getService() as one. (Rather, I would just describe ServiceFactory as a "factory" at leave it at that.) The benefits of ServiceFactory.getService() are the same as those of a factory method, plus the usual benefits of having an instance instead of a static method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download