常见设计模式

1. 写出 构造函数模式、混合模式、模块模式、工厂模式、单例模式、发布订阅模式的范例。
//工厂模式
function createPerson (name,age) {
    var person = {
        name:name,
        age:age
    }
    person.sayName = function(){
        console.log(this.name)
    }
    return person
}

//构造函数模式
function Person(name,age){
    this.name = name
    this.age = age
}
Person.prototype.sayName = function(){
    console.log(this.name)
}

//混合模式
function Person(name,age){
    this.name = name
    this.age = age
}
Person.prototype.sayName = function(){
    console.log(this.name)
}
function Stundent(name,age,school){
    Person.call(this,name,age)
    this.school = school
}
function objCreate(obj){
    function F(){}
    F.prototype = obj
    return new F()
}
Stundent.prototype = objCreate(Person.prototype)
Stundent.prototype.constructor = Stundent
Stundent.prototype.saySchool = function(){
    console.log(this.school)
}

//模块模式
var person = (function(){
    name = '小明'
    function sayName(){
        console.log(name)
    }
    return {
        name:name,
        sayName:sayName
    }
})()

//单例模式
var person = (function(){
    var instance
    function init(name){
        return{
            name:name
        }
    }
    return{
        createPerson:function(name){
            if(!instance){
                instance = init(name)
            }
            return instance
        }
    }
})()

//订阅发布模式
var eventCenter = (function(){
    var events = {}
    function on(event,handler){
        events[event] = events[event]||[]
        events[event].push({
            handler:handler
        })
    }
    function off(event){
        delete events[event]
    }
    function trigger(event,arguments){
        if(!events[event]) return;
        events[event].forEach(function(ele,index){
            ele['handler'](arguments)
        })
    }
    return{
        on:on,
        off:off,
        trigger:trigger
    }
})()
2. 使用发布订阅模式写一个事件管理器,可以实现如下方式调用
var Event = (function(){
    var events = {}
    function on(event,handler){
        events[event] = events[event]||[]
        events[event].push({
            handler:handler
        })
    }
    function off(event){
        delete events[event]
    }
    function fire(event,val){
        if(!events[event]) return;
        events[event].forEach(function(ele,index){
            ele['handler'](val)
        })
    }
    return{
        on:on,
        off:off,
        fire:fire
    }
})()
Event.on('change', function(val){
    console.log('change...  now val is ' + val);  
});
Event.fire('change', '饥人谷');
Event.off('change');

你可能感兴趣的:(常见设计模式)