mardi 14 juin 2016

Which design pattern to follow in creation of objects with Javascript?

Module Pattern (or) Prototype Pattern

Use Case : I have to create multiple objects, but the base class is not get any derived class, I can use module pattern with common global functions instead with prototype.

for Example:

code 1: (module pattern)

var globals = {
   method1 : function(){
       console.log("global method"); 
   }
}
function closureModule(){
    obj = {};
    obj.commonMethod = globals.method1;
    function pvtMethod(){
        console.log("private");
    }
    obj.privateMethod = pvtMethod
    return obj;
}
var o1 = closureModule();
var o2 = closureModule();
.
.
.
.
var o100 = closureModule();

code 2 : (prototype pattern)

function base(key){
    this.KEY = key;
}

base.prototype.commonMethod = function(){
    console.log("common Method", this);
}

var o1 = new base("0");
var o2 = new base("1");
.
.
.
.
var o100 = new base("100");

Aucun commentaire:

Enregistrer un commentaire