+ 6
In OO languages, what is the advantage of using factory methods and private constructors to create objects?
What's the advantage over using a public constructor and no factory method?
3 Réponses
+ 4
Sometimes you have to. Depens on the language!
Consider this C++ class:
class Foo {
const Bar bar;
}
You ought to initialize `bar` in the constructor initializer and not in the constructor body, because it is const. But maybe `Bar` has no straightforward constructor to use, or you need to do some work before you can create a `Bar` object.
Your only option is to pass an already working `Bar` to the constructor of `Foo`:
Foo(Bar b) : bar(b) { }
That ctor can be private, and a factory method takes care of creating the `Bar` object first.
In Javascript (or python, php etc) there is no method overloading and therefor no constructor overloading, which naturally leads to factory methods like
class Foo {
constructor () {}
static fromBar(bar) { ... }
static fromQux(qux) { ... }
}
Another semi-common usecase is the singleton pattern, where a factory method makes sure that there is only one instance of your class.
All in all factory methods add extra flexibility I'd say.
Edit: Letters
+ 2
~ swim ~ Sure but that doesn't solve the problem our hypothetical `Bar` class is having.
+ 2
But if `Bar` doesn't have a proper constructor applicable for the ctor initializer then it's even less applicable while declaring a class. :/