design-patternsfactory-patternfactory-methodstatic-factory

Is it forbidden to use static methods in factory pattern?


I got told that using static methods when implementing the factory-method-pattern is wrong and should be avoided. Because I wasn't really familiar with the pattern I accepted that answer.

After reading articles and getting deeper into it, I couldn't find any source which supports this statement.

Can someone help me out with this situation. Should I avoid the static-keyword in factory-methods and if so, when are they useful?


Solution

  • The first thing to be 100% clear about is that there is no single "Factory Pattern". The term Factory describes a category of patterns with wildly differing implementations. When someone says Factory Pattern they could be talking about any creational pattern; but most commonly the phrase Factory Pattern indicates ignorance of design patterns.

    Two very specific Factory Patterns are published in the famous Gang of Four book: Abstract Factory and Factory Method.

    Static Factory was popularized by Joshua Bloch in Effective Java. There is no relationship between Bloch's Static Factory Method and the GoF's Factory Method, other than having similar names.

    I will adjust the original question then, to provide a clear answer.

    Is it forbidden to use static methods in the GoF Factory Method pattern?

    Yes. The GoF pattern requires inheritance, which is not supported by static methods. This does not make the Static Factory pattern less useful! Static Factory is a perfectly legitimate design pattern that happens to be implemented in a very different way from the GoF Factory Method pattern. You may use both patterns when appropriate; and now you can label them appropriately as well.