Skip to content

Instantly share code, notes, and snippets.

@Go7hic
Last active February 7, 2017 03:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Go7hic/f0f4007743f38cba16aa to your computer and use it in GitHub Desktop.
Save Go7hic/f0f4007743f38cba16aa to your computer and use it in GitHub Desktop.
JS 设计模式 #tags: 设计模式
// 策略模式
var validator = {
types: {},
messages: [],
config: {},
validate: function (data) {
var i, msg, type, checker, result_ok;
this.messages = [];
for (i in data) {
if (data.hasOwnProperty(i)) {
type = this.config[i];
checker = this.types[type];
if (!type) {
continue; // no need to validate
}
if (!checker) { // uh-oh
throw {
name: "ValidationError",
message: "No handler to validate type " + type
};
}
result_ok = checker.validate(data[i]);
if (!result_ok) {
msg = "Invalid value for *" + i + "*, " + checker.instructions;
this.messages.push(msg);
}
}
}
return this.hasErrors();
},
// helper
hasErrors: function () {
return this.messages.length !== 0;
}
};
validator.config = {
first_name: 'isNonEmpty',
age: 'isNumber',
username: 'isAlphaNum'
};
// checks for non-empty values
validator.types.isNonEmpty = {
validate: function (value) {
return value !== "";
},
instructions: "the value cannot be empty"
};
// checks if a value is a number
validator.types.isNumber = {
validate: function (value) {
return !isNaN(value);
},
instructions: "the value can only be a valid number, e.g. 1, 3.14 or 2010"
};
// checks if the value contains only letters and numbers
validator.types.isAlphaNum = {
validate: function (value) {
return !/[^a-z0-9]/i.test(value);
},
instructions: "the value can only contain characters and numbers, no special symbols"
};
// 工厂模式 自然工厂
function CarMaker() {
CarMaker.prototype.drive = function(){
return "Vroom, Ihave" + 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();
}
newcar = new CarMaker[constr]();
return newcar;
};
CarMaker.Compact = function() {
this.doors = 4;
}
// 内置对象工厂
var o = new Object()
o.constructor === Object;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment