Factory implemented with static method

taskinoor picture taskinoor · Apr 18, 2011 · Viewed 7.4k times · Source

I have seen an implementation of Factory using static methods. Something like this:

public class MyFactory {
    public static Product1 createProduct1() {}
    public static Product2 createProduct2() {}
}

p1 = MyFactory.createProduct1();
p2 = MyFactory.createProduct2();

I am not sure whether I can call it Abstract Factory, but that is not the question. What I understand about Abstract Factory is that it gives us the flexibility to change the product families easily.

Factory factory = new MyFactory();  // might be a global or Singleton
p1 = factory.createProduct1();
p2 = factory.createProduct2();

And if I want to change from MyFactory to YourFactory then only one line is required to change. I can also change that in run time. But is it possible if they are implemented as static method? I need to change all the calls to static factory. And also need to use if-else checking in every places if we want to decide at run time.

p1 = YourFactory.createProduct1();
p2 = YourFactory.createProduct2();

So what is the benefit of implementing factory using static methods? Are not we loosing the main flexibility? What have I missed here?

Please note that no specific language is assumed. Any help is appreciated.

Answer

Mike Valenty picture Mike Valenty · Apr 18, 2011

With static methods like that, you get some code reuse but that's about the extent of the benefit. It essentially reduces the oo pattern to a procedural paradigm. The big thing that you miss out on is changing your implementation at runtime based on context.

A singleton is only slightly better. It enables you to write your logic normally with member variables (state) and then just make a couple of tweaks to turn it into a singleton. Let's say your were doing some instance pooling in your factory, a singleton might be a good fit there. You still miss out on context though.

The most flexible pattern is to use dependency inversion, meaning your class depends on a factory abstraction and doesn't know or care if it's a singleton or not. This enables you to consider the context when supplying the concrete factory to use.