Working with GoF's Design Patterns in JavaScript Programming
page 3 of 8
by Xianzhong Zhu
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 80515/ 177

Working with the Factory Method Pattern

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.


View Entire Article

User Comments

No comments posted yet.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2019 ASPAlliance.com  |  Page Processed at 2019-08-24 11:13:47 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search