Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
design pattern
//
// singleton pattern
//
var Singleton = (function(){
var instance;
return function(){
if(instance){
return instance;
};
instance = this;
}
})();
var sing1 = new Singleton();
var sing2 = new Singleton();
console.log(sing1 === sing2) // true
Singleton.prototype.test = 'test';
var sing3 = new Singleton();
console.log(sing3.test); // test
console.log(sing1.test); // test
//
// factory pattern
//
function CarMaker(){};
CarMaker.prototype.drive = function(){
return 'Vroom, I have '+ this.doors + ' doors';
};
CarMaker.factory = function(type){
var constr = type,newcar;
if(typeof CarMaker[constr] !== 'function'){
throw{
name:"error",
message:constr + ' doesn\'t exist'
}
};
if(typeof CarMaker[constr].prototype.drive !== 'function'){
 CarMaker[constr].prototype = new CarMaker();
};
console.log('a');
newcar = new CarMaker[constr]();
return newcar;
};
//--------------------------------------
CarMaker.Compact = function(){
this.doors = 4;
};
CarMaker.Convertible = function(){
this.doors = 2;
};
CarMaker.SUV = function(){
this.doors = 17;
};
//--------------------------------------
var corolla = CarMaker.factory('Compact');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.