Created
March 27, 2011 02:13
-
-
Save yokotak0527/888852 to your computer and use it in GitHub Desktop.
design pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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