Suppose that you don't know the exact class that should be created until runtime. In the case of JavaScript, this may be due to browser differences. The best example of this today is in creating XMLHttp objects. A lot of times, you'll see code that looks like this:
if (typeof XMLHttpRequest != "undefined") {
return new XMLHttpRequest();
} else if (typeof window.ActiveXObject != "undefined") {
return new ActiveXObject("MSXML2.XMLHttp");
}
Clearly, you don't want to repeat this code every time you need to create a new XMLHttp object.
The factory pattern involves having a function (or an object with a method) that returns the appropriate object. Developers need not know which object is being returned since the interface will be the same no matter what. You need only call the function and know that the correct object will be returned. For example:
function XMLHttpFactory() {
}
XMLHttpFactory.createXMLHttp = function () {
if (typeof XMLHttpRequest != "undefined") {
return new XMLHttpRequest();
} else if (typeof window.ActiveXObject != "undefined") {
return new ActiveXObject("MSXML2.XMLHttp");
}
}
With this defined, developers can now use a single method call to create the object that will work for their environment:
var oXMLHttp = XMLHttpFactory.createXMLHttp();