1.简单工厂模式
function fn(id,txt){
var o = new Object();
o.txt = txt;
if(id == "a"){
o.show = function(){
console.log("a:" + this.txt);
}
}
if(id == "b"){
o.show = function(){
console.log("b:" + + this.txt);
}
};
return o;
}
var fa = new fn("a","test");
fa.show();
2.工厂方法模式
(安全模式最好建立在安全模式基础下,先用instanceof判断作用域)
通过参数,返回需要的实例对象
var Factory = function (type, con) {
if (!(this instanceof Factory)) {
return new Factory(type, con);
} else {
var s = new this[type](con);
}
};
Factory.prototype = {
a: function (con) {
console.log("a:" + con);
},
b: function (con) {
console.log("b:" + con);
}
};
var fn = new Factory("a","test");
3.抽象工厂模式
有点不能理解,看完再写。。。
4.建造者模式
用多个构造函数的实例,构造一个整体
//人类
var Human = function(param) {
//技能
this.skill = param && param.skill || "保密";
//兴趣爱好
this.hobby = param && param.hobby || "保密";
};
Human.prototype = {
getSkill: function() {
return this.getSkill;
}
};
//姓名
var Named = function(name) {
var _this = this;
(function(name, _this) {
_this.wholeName = name;
if (name.indexOf(" ") > -1) {
_this.firstName = name.slice(0, name.indexOf(" "));
_this.lastName = name.slice(name.indexOf(" "));
}
})(name, _this);
};
//职位
var Work = function(work) {
var _this = this;
(function(work, _this) {
switch (work) {
case "code":
_this.work = "程序员";
_this.des = "写代码的"
break;
}
})(work, _this);
};
/*
应聘者建造者
*/
var Person = function(name, work) {
var _person = new Human();
_person.name = new Named(name);
_person.work = new Work(work);
return _person;
};
var xiaoming = new Person("xiao ming", "code");
console.log(xiaoming.skill);
console.log(xiaoming.name.lastName);
5.原型模式。
看懂再写。。。
6.单例模式
类似jquery的方式,把变量方法都封装起来,只暴露一个命名对象出来。
var fn = {
a:function(){
console.log(a);
}
c:function(){
return this.a();
}
};
利用单例模式来保存不让修改的静态变量
var Conf = (function() {
var _conf = {
"MAX": 100,
"MIN": 1
};
//返回静态变量的取值方法
return {
get: function(name) {
return _conf[name] ? _conf[name] : null;
}
}
})();
var a = Conf.get("MAX");
console.log(Conf);
console.log(a);
静态变量的惰性单例
var lazyS = (function() {
var _i = null;
function s() {
return {
"MAX": 100,
"MIN": 1
};
};
//获取单例
return function() {
if (!_i) {
_i = s();
}
return _i;
}
})();
var a = lazyS();
console.log(a);