Factory Methods vs. Factory Classes in Java

|

There are a number of cases in Java where I find myself wanting to use a variant of the factory method pattern. For example:

  • To control the number of objects created, or to create a limited set of objects (one per value of an enumeration for example, this could use an backed map in J2SE 5);

  • To perform some checks before creating object. Like init() called before instantiating instead of after.

Often my instinct here is to add some static methods to the class and make the constructors private. I think that in part this comes from the pattern name: factory method, I think a better name would have been factory class, or maybe just factory. Anyway, doing this has some advantages in that it reduces the number of classes that need writing and keeps all of the code in one place. Like this:

Factory Method

But there are drawbacks as well. The main one being that I cannot then treat the factory like a bean, this makes it more difficult to display in UI (by preventing the use of common binding frameworks for example). So a better approach is more like this:

Factory Class

Note that this is still one class short of the pattern described in the Wikipedia article. The Creator interface is just unnecessary as far as I’m concerned (although there is a case for it’s existence in scenarios like the various Java SPI-style interfaces).

About this Entry

This page contains a single entry by Ian Phillips published on December 8, 2006 12:07 AM.

RvSnoop 356 was the previous entry in this blog.

Oh, Such a Good Infrastructure is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Pages

Powered by Movable Type 4.1