Skip to content

Instantly share code, notes, and snippets.

@fwon
Created October 21, 2014 15:10
Show Gist options
  • Save fwon/3394e0c2b4c25d39c80d to your computer and use it in GitHub Desktop.
Save fwon/3394e0c2b4c25d39c80d to your computer and use it in GitHub Desktop.
工厂模式
//工厂模式
function Factory () {}
Factory.prototype.defaultGender = Boy;
Factory.prototype.createFactory = function (options) {
if (options.name === 'girl') {
this.defaultGender = Girl;
} else {
this.defaultGender = Boy;
}
return new this.defaultGender(options);
}
var factory = new Factory();
var instance = factory.createFactory({name: 'boy'});
//抽象工厂模式
var factory = (function() {
var types = {
boy: Boy,
girl: Girl
};
return {
getClass: function(type, options) {
if(type && types[type]) {
var Gender = types[type];
return (Gender) ? new Gender(options) : null;
}
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment