Search code examples
design-patternsfactoryfactory-patternfactory-methodstatic-factory

Factory Pattern - CreateInstance static or not?


This is about the Factory Pattern. I am a little confused.

I saw implementations where the createInstance() method is static and some implementations that are non-static.

Some say it's depending on "style" or "taste" and some say it does not. Wikipedia says that it should be non-static, and http://www.dofactory.com/Patterns/PatternFactory.aspx also says that it should be non-static, according to the Gang of Four.

My question is: does it depend on style & taste or does it violate the Factory Pattern if it's implemented the static way? What's right?


Solution

  • Static method doesn't violate the pattern but it goes against many other object oriented practices (inversion of control + dependency injection as one example) so using instances is better.

    Edit:

    I just got some badge for this answer but when I read it I could not believe my eyes. It is wrong when we strictly speak about GoF Factory method pattern and it deserves some correcting.

    You can have static CreateInstance method for creating instance of a type - there is nothing wrong about that - people often call it factory method but that is not what is called Factory Method pattern. Once you start putting logic into this method to create instances of different types depending on some condition you may be actually in need of Factory Method pattern described by GoF.

    The point of GoF Factory method pattern is to replace conditional logic inside CreateInstance with inheritance and polymorphism and thus it cannot be static. Factory method is an instance method - moreover it is virtual. Your base type has usually abstract CreateInstance and conditional logic is replaced by inheritance tree where each subtype overrides CreateInstance and creates just specific product for that subtype.