设计模式

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

let student = new Person('tyy',25)
  • 工厂模式
function craetePerson(name){
  var person = {
    name: name,
    sayName: function(){
      console.log(this.name)
    }
  }
  return person
}
craetePerson('tyy')
  • 单例模式
var People = (function(){
  var instance
  function init(name){
    return {
      name: name
    }
  }
  return {
    craetePeople: function(name){
      if(!instance){
        instance = init(name)
      }
      return instance
    }
  }
}())
People.craetePeople('tyy') //{name: 'tyy'}
People.craetePeople('yyt') //{name: 'tyy'}
单例模式内部有次判定,当第二次创建时不会建立新的引用
  • 模块模式
var Person = (function(){
  var name = 'tyy'
  function sayName(){
    console.log(name)
  }
  return {
    name: name,
    sayName: sayName
  }
})()
  • 订阅发布模式
var EventCenter = (function () {
  var events = {};
  //('hello',function(){})
  function on(evt, handler) {
    //判断events里有没有events['hello'],如果没有events['hello']=[]
    events[evt] = events[evt] || [];
    // events['hello']=[{ handler: handler}]
    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);
      // 遍历数组,执行handler
    }
  }
  // 取消订阅
  function off(evt){
     delete events[evt]
  }

  return {
    on: on,
    fire: fire,
    off: off   // 取消订阅
  }
})();

EventCenter.on('hello', function () { console.log('hello') })

EventCenter.fire('hello')

  • 混合模式(待续...)

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