First of all, let us look at the definition of the Factory
Method pattern.
(1) Concept
According to the GoF's definition, the purpose of the
Factory Method pattern is to define an interface to create objects, while it is
the sub classes' responsibility to decide which class to instantiate. More
accurately, the Factory Method pattern transfers the responsibility of creating
instantiations to the factory class, and makes use of the abstract principle to
delay the instantiation behavior to concrete factories.
(2) Example
Under some conditions, we really cannot make sure the object
to establish corresponds to which class' instantiation. Such a typical example is
to establish the XMLHttpRequest (XHR) object in the Ajax applications, because
everyone knows the implementation of the XHR object is different in different
browsers.
With the help of the Factory Method pattern, we can easily establish
the generally-used XHR object in JavaScript. The corresponding code of such an implementation
is as follows.
Listing 7
function XMLHttpFactory(){}
XMLHttpFactorv.CreateXMLHttp=function() {
if(typeof XMLHttpRequest!=”undefined”){
//for browsers( such as Firefox) that support
the XMLHttpRequest object
return new XMLHttpRequest();
}
else if(typeof window.ActiveXObject
!=”undefined”)
{
// for browsers( such as IE) that support
// the ActiveX object
return new ActiveXObject(“MSXML2.XMLHttp”);
}
}
Then, using the following code you can easily judge the type
of the target browser and then establish the proper XHR object.
var xmlhttp=XMLHttpFactory.createXMLHttp();
Henceforth, you can carry out the server-side invocation in
your Ajax styled applications according to the XHR object established above.