各种设计模式混搭
-
模块模式
运用场景:使用简单的导出一个对象使用
var Person = (function(){ var name = 'huangchucai' function sayName(){ console.log(name) } return {name,sayName} })()
-
构造函数模式
运用场景:一个组建,功能稍微复杂点的时候使用
function Person(name,age){ this.name = name; this.age = age; } Person.prototype.sayName = function(){ return this.name } var student = new Person('hcc',22) console.log(student);
-
混合模式(继承和构造函数)
运用场景:要利用继承来实现相应的功能
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 = Object.create(Person.prototype); Student.prototype.sayScore = function(){ console.log(this.score); } var student = new Student("hcc", 28, 99); console.log(student);
-
工厂模式
运用场景:适用于创建一个对象
- 调用一个函数
- return 一个对象
- 这个对象有需要的方法和属性
// 想象一下,批量的生产对象 function createPeople(opts){ var people = { name : opts.name || 'huangchucai' } people.sayName = function(){ console.log(this.name) } return people } var p1 = createPeople({name:'hcc'}) p1.sayName() // hcc var p1 = createPeople({name:'yx'})
-
单例模式
运用场景:常见一个对象,在整个作用域下都是独立无二的,不管怎么使用,都是同一个方法。
var People = (function(){ var instance function init(){ // dosomething return { name: 'hcc', age: 22 } } return { createPeople: function(){ if(!instance){ instance = init() } return instance } } })() var obj1 = People.createPeople(); var obj2 = People.createPeople();
-
发布订阅模式
**运用场景: **
var EventCenter = (function(){ var events = {} function on(evt,handle){ events[evt] = events[evt] || [] events[evt].push({ handler: handler }); } function fire(evt,args){ if(!events[evt]){return} for(let i=0;i<events[evt].length;i++){ events[evt][i].handler(args); } } return { on: on, fire: fire } })() //events{evt:[my_event]} EventCenter.on('my_event', function(data){ console.log('my_event received...'); }); EventCenter.on('my_event', function(data){ console.log('my_event2 received...'); });
let EventCenter = (function() {
const F = function() {
this._objEvent = {};
}
F.prototype.on = function(eventName,callback) {
this._objEvent[eventName] = this._objEvent[eventName] || [];
this._objEvent[eventName].push(callback)
}
F.prototype.triggle = function(eventName,params) {
if(!this._objEvent[eventName]) return
this._objEvent[eventName].forEach(fn => {
fn(params)
})
}
return F
})()
var event = new EventCenter()
event.on('hello',() => {
console.log('hello')
})
event.on('xxxx',() => {
console.log('hello world')
})
event.triggle('hello')
event.triggle('xxxx')
网友评论