William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

JavaScript: Factory Pattern

JavaScript: Factory Pattern

The following is a typical Factory pattern for JavaScript, original from Stoyan Stefanov.

 //1. constructor:
function CarMaker() {}

//2. Factory Items Iteration:
CarMaker.Compact = function(){};
CarMaker.Convertible = function(){};
CarMaker.SUV = function() {};

//3. public methods:
CarMaker.prototype.tool = function() {};
CarMaker.prototype.drive = function() {};

//4. Static methods:
CarMaker.factory = function(type) {
  var constr = type;
  
  if(typeof CarMaker[constr] !== 'function') {
     throw {
       name: "Error",
       message: constr + 'not exist'
     };
  }
  //inheritance only once
  if(typeof CarMaker[constr].prototype.tool !== 'function') {
    CarMaker[constr].prototype = new CarMaker();
  }
  
  return new CarMaker[constr]();
} 

//5. Usage:
var camry = CarMaker.factory('Convertible');
var cherokee = CarMaker.factory('SUV');
camry.tool();
cherokee.drive(); 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: