Originally posted by Kevin Lillybridge:
I'm creating a dialog box where I would like to use a static factory method as opposed to a public constructor.
Now this sounds like it is straight out of
Effective Java: "Item 1: Consider providing static Factory methods instead of constructors". (Version for the 2nd Edition:
Chapter 2: Creating and Destroying Objects)
The advantages listed are:
static factory methods can have meaningful names static factory methods don't have to return new objects. static factory methods can return subtypes. The greatest advantage is that it can return subtypes. However this refactoring seems to suggest "I need looser coupling". Towards that objective very little progress has been made. You are replacing concrete constructors (making you dependent on the concrete classes) with static methods on a concrete class (making you directly dependent on the concrete class implementing the static factory methods and the interfaces returned by the static methods - the point is that you are still "dependent on implementations, not just interfaces". To drive this to its logical conclusion
you should really go further:
You already have class A and B. Now create interface I and J and let class A and B implement them. Create an interface K that has getI(args) and getJ(args) methods on it. Create a class F that implements K and creates class A instances in getI(args) and creates class B instances in getJ(args). Modify your dialog box so that you can (dependency) inject a class that implements K either in the dialog box constructor or through a mutator (setter) method. Now your dialog box can use the instance that implements K to obtain instances that implement I or J. So the dialog box now depends on interfaces I,J,K, not classes A,B,F. The dialog box code is now truly "programming to interface and not to implementation" Your coupling has now been loosened - but with it comes with some increase in complexity so you need to be sure that your gain outweighs the cost before you apply this. However this technique has been heavily favored since developers have been using
unit test frameworks like
JUnit because it gives them flexibility to "inject" instrumented mock versions of the classes for the purpose of unit testing.
Micheal Feathers: The Humble Dialog Box (PDF) Daniel Gartner: Writing More Testable Code with Dependency Injection Martin Fowler: Inversion of Control Containers and the Dependency Injection pattern [ May 13, 2008: Message edited by: Peer Reynders ]