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?
I'm very hesitant to categorize "instance versus static" as a matter of taste. This sort of implies that it's aesthetic like a favorite color or, more appropos, camelCase versus PascalCase.
Instance versus static is more a question of tradeoffs. With instance members of any kind, you get all of the benefits of polymorphism, since you can implement interfaces and inherit from other classes when you have instances and instance members. With statics, you do not get these benefits. Generally, static versus instance is a tradeoff for up-front simplicity versus downstream simplicity. Statics are easy because they are globally accessible and you don't have to consider things like "when should this be instantiated and by whom?" You don't have to pass them around with accessors/mutators or constructors, and your API looks cleaner. This makes up front reasoning easier. But, it makes maintenance and future implementations harder.
If you have a static method -- say a factory method in your case -- and you later want it to behave differently in certain situations, you're kind of hosed. You have to make a second method and copy and paste the functionality minus whatever you want to change, and then have clients figure it out. Or, worse, you expose a global variable and have clients set this before and after using your method, with the global telling the method how to behave.
If you had gone the instance route up front, this would be easy. You'd just inherit and override your initial factory method and provide the derived classes where you need the new functionality. You're not placing additional burden on client code and you're making almost no modifications to existing classes (open/closed principle).
My advice would be to do future you and/or other maintainers a favor and use the instance implementation. It's not a matter of what the Gang of Four or anyone else want or prefer - it's a matter of your own sanity in the face of code rot.