JavaScript: the Factory design pattern

The Factory design pattern is designed to create new object instances depending on the argument passed to the constructor. In JavaScript, the implementation of this design pattern is rather straightforward. All we have to do is to create a new function which accepts an object as its argument. Depending on the type of object passed in, it will return the appropriate object instance or an empty object if no argument has been specified.

(function() {

  var A = function() {
  
    this.property = 'Test 1';
  
  };
  
  var B = function() {
  
    this.property = 'Test 2';
  
  };
  
  var Factory = function(obj) {
  
    obj = obj || {};
        
    switch(obj) {
    
      case A:
      
        return new A();
        
      case B:
      
        return new B();
        
      default:
      
        return obj;
    
    }
  
  
  
  };
})();

A simple test:

var a = Factory(A);
console.log(a.property); // 'Test 1'
    
var b = Factory(B);
console.log(b.property); // 'Test 2'
    
var o = Factory();
console.log(typeof o); // object

As you can see, we've used a switch construct to determine what kind of object we have to return.

Leave a Reply

Note: Only a member of this blog may post a comment.