I am learning the Javascript tips from this http://code.google.com/p/jslibs/wiki/JavascriptTips site.
I came to see about the Factory method pattern. They shown the following example
Complex = new function() {
function Complex(a, b) {
// ...
}
this.fromCartesian = function(real, mag) {
return new Complex(real, imag);
}
this.fromPolar = function(rho, theta) {
return new Complex(rho * Math.cos(theta), rho * Math.sin(theta));
}
}
var c = Complex.fromPolar(1, Math.pi); // Same as fromCartesian(-1, 0);
But I can’t guess why actually this is called as Factory method pattern. I want to know about this Factory method pattern and advantage of using this and especially to know where to exactly use this.
The Factory pattern may be described as a function that creates a class instance (like a real factory produces cars or toys, etc.) In your example, Complex is a factory that can create instances in two ways: cartesian or polar.
The Factory pattern is useful in a number of scenarios, including: