design_pattern_code

1.构造函数,最后通过new的形式调用

function Person(name,age){
    this.name=name
    this.age=age
}
Person.prototype.sayName = function(){
    return this.name
}
var man = new Person('asan',3)

2.混合模式,原型链的继承

function Person(name,sex){
    this.name = name;
    this.sex = sex;
}
Person.prototype.getName = function(){
    console.log('my name is '+this.name)
};
function Male(name,sex,age){
    Person.call(this,name,sex);
    this.age = age;
}
Male.prototype = Object.create(Person.prototype);
Male.prototype.getAge = function(){
    console.log(this.age)
};
var man = new Male('asan', 'm', 17);
man.getName();//my name is asan

3.模块模式,通过闭包来实现一个模块

var Person = (function(){
    var name = "asan"
    function sayName(){
        console.log(name)
    }
    return {
        name:name,
        sayName:sayName
    }
})

4.工厂模式,创建不同的引用方式

function createPerson(name){
    var person={
        name:name,
        sayName:function(){
            console.log(this.name)
        }
    }
    return person
}

5.单例模式,匿名函数,不会创建一个新的 而是引用一个原先的

var People = (function(){
    var instance;
    function init(name){
        return{
            name:name
        }
    }
    return {
        createPerson: function(name){
            if(!instance){
                instance= init(name)
            }
            return instance
        }
    }
}())

6.发布订阅模式

var EventCenter=(function(){
    var events={};

    function on(evt,handler){
        events[evt]=events[evt] || [];
        events[evt].push({
            handler:handler
        })
    }
    function fire(evt,arg){
        if(!events[evt]){
            return 
        }
        for(var i=0;i

使用发布订阅模式写一个事件管理器,可以实现如下方式调用

Event.on('change', function(val){
    console.log('change...  now val is ' + val);  
});
Event.fire('change', '饥人谷');
Event.off('changer');
var Event = function(){
    this.events={}
}

Event.prototype.on = function(topicName,callback){
    this.events[topicName] = this.events[topicName] || []
    this.events[topicName].push({
        callback:callback
    })
}
Event.prototype.fire = function(topicName,arg){
    if(events[topicName]){
        events[topicName].forEach(function(callback){
            callback.apply(this,arg)
        })    
    }
}
Event.prototype.off = function(topicName){
    delete this.events[topicName]
}
Event.on('change', function(val){
    console.log('change...  now val is ' + val);  
});
Event.fire('change', '饥人谷');
Event.off('change');

你可能感兴趣的:(design_pattern_code)