Javascript 设计模式

  1. 构造函数模式
var People = function (name, age) {
    this.name = name
    this.age = age
    this.sayName = function () {
      console.log(this.name)
    }
}
var person = new Person('Lucifer', 18)
person.sayName()
  1. 混合模式
var Person = function (name, age) {
    this.name = name
    this.age = age
}
Person.prototype.sayName = function () {
    console.log(this.name)
}
var Student = function (name, age, num) {
    Person.call(this, name, age)
    this.num = num
}
Student.prototype = create(Person.prototype)
function create (parentObj) {
    function F () {}
    F.prototype = parentObj
    return new F()
}
Student.prototype.sayNum = function () {
    console.log(this.num)
}
var student = new Student('Lucifer', 22, 1)
student.sayName()
student.sayNum()
  1. 模块模式
var Person = (function () {
    var name = 'Lucifer'
    function sayName () {
      console.log(name)
    }
    return {
      name: name,
      sayName: sayName
    }
})()
Person.sayName();
  1. 工厂模式
function create (opts) {
    var person = {
      name: opts.name || 'Lucifer'
    }
    person.sayName: function () {
      console.log(this.name)
    }
    return person;
}
var p1 = create({ name: 'LN' })
  1. 单例模式
var singleton = (function () {
    var instance
    function init () {
      // define private methods and properties
      // do something
      return {
        // define public methods and properties
      }
    }
    return {
      getInstance: function () {
        if (!instance) {
          instance = init();
        }
        return instance;
      }
    }
})();
  1. 发布订阅模式
var EventCenter = (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)
      }
    }
    return {
      on: on,
      fire: fire
    }
})()
EventCenter.on('my_event', function (data) {
    console.log('my_event received...')
})
EventCenter.fire('my_event')

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