First of all, let us still look at the definition of the
Façade pattern.
(1) Concept
The Façade pattern can define the homologous interfaces for
a set of sub systems. The true secrets behind the Façade pattern lies in that
it can define a high-level interface with which to make all the sub systems more
easily to use. A typical illustration of the Façade pattern in developing Web applications
is to implement a uniform API with which to remove the differences of various
browsers in realizing the concrete characteristics.
Let us next still see a related example.
(2) Example
In constructing the Ajax based Web applications, when we use
the XHR object to request the server-side data, we usually utilize the
following steps to code:
·
Create the XHR object.
·
Register the related callback function.
·
Set the request mode (POST or GET), URL, and pattern (synchronously
or asynchronously) with the open method.
·
Send out the request with the send method.
·
Supervise the states of the request, and if the special request
is met, then perform the specified function.
As you've guessed here, using the XHR object is rather complicated,
in each of the above steps you have to consider the browser-compatible related problems.
Below, we will show you the basic application of the Façade pattern
through a simple example. The target of the example is to output a line to
welcome information hinting the browser type the current user is using. For the
sake of simplicity, we are only to distinguish the IE from other types of browsers
in the example. The key and related code is shown as follows:
Listing 21
//IE
function IEBrowser() {
this.hello=function(){
alert(”IE browser”);
}
}
//Non-IE browser
function NonIEBrowser() (
this.hello =function(){
alert("Non-IE browser");
}
}
//The Façade object
var Facade={};
Facade.hello=function(){
var browser;
// IE
if(window.ActiveXObject)
browser=new IEBrowser();
//Non-IE browser
else
browser=new NonIEBrowser();
Browser.hello();
};
The "Facade.hello" method above establishes
different browser objects according to the browser type and invokes the
corresponding hello methods. So, for the developers, they
do not need to consider the browser type, but only focus on invoking the hello method of the Facade object.
Moreover, the IE browser and Non-IE browser are two types of
independent classes, both of whose internal realizations may change in the
future, but this will not influence the exterior object Facade to invoke them,
namely the "Facade.hello" method related code does not need to be
changed.