Web40.设计模式
2017-12-20 本文已影响13人
FiredEarthMusic
构造函数模式
//constructor
function Person(name, age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
return this.name;
};
var student = new Person("fem", 30);
混合模式
//mixing
//混合原型
//一般在继承的时候用
//student继承person
var Person = function(name, age){
this.name = name;
this.age = age;
};
Person.prototype.sayName = function(){
console.log(this.name);
}
var Student = function(name, age, score){
Person.call(this, name, age);
this.score = score;
}
Student.prototype = create(Person.prototype);
function create(parentObj){
function F(){}
F.prototype = parentObj;
return new F();
}
Student.prototype.sayScore = function(){
console.log(this.score);
}
var student = new Student("fem", 28, 99);
模块模式
//module
var Person = (function(){
var name = 'ruoyu';
function sayName(){
console.log(name);
}
return {
name: name,
sayName: sayName
}
})()
工厂模式
//factory
//每次创建一个新的引用
function createPerson(name){
var person = {
name: name,
sayName: function(){
console.log(this.name);
}
}
}
createPerson('fem');
createPerson('emmmmm');
单例模式
//singleton
//匿名函数 ==> lambda函数
//节约内存
//比如对话框
var People = (function(){
var instance;
function init(name){
return {
name:name
};
}
return {
createPeople: function(name){
if (!instance){
instance = init(name);
}
return instance;
};
}
}());
People.createPeople('fem') //{name: 'fem'}
People.createPeople('emmm') //{name: 'fem'}
发布订阅模式
//publish subscribe
var EventCenter = (function(){
var events = {}; //存储所有的key value
function on(evt, handler){
events[evt] = events[evt] || []
events[evt].push({
handler: handler
})
}
function fire(evt, args){
if(!events[evt]){
return;
}
for(var i=0; i<events[evt].length; i++){
events[evt][i].handler(args);
}
}
function off(name){
delete events[name]
}
return {
on: on,
fire: fire,
off: off
}
})();
使用发布订阅模式写一个事件管理器,可以实现如下方式调用
Event.on('change', function(val){
console.log('change... now val is ' + val);
});
Event.fire('change', '饥人谷');
Event.off('changer');
var Event = (function(){
var events = {}
function on(evt, handler){
events[evt] = events[evt] || []
events[evt].push({
handler: handler
})
}
function fire(evt, args){
if(!events[evt]){
return;
}
for(var i=0; i<events[evt].length; i++){
events[evt][i].handler(args);
}
}
function off(name){
delete events[name]
}
return {
on: on,
fire: fire,
off: off
}
})()