1.写出 构造函数模式、混合模式、模块模式、工厂模式、单例模式、发布订阅模式的范例。
JS设计模式大全
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
console.log(this.name)
}
let person = new Person('hh',28)
console.log(person)
function createPerson(name,age){
return {
name: name,
age: age,
sayName: function(){
return name
}
}
}
console.log(createPerson('hh',28))
let Person2 = (function singleton(){
var instance
function init(name,age){
return {
name: name,
age: age
}
}
return {
createPerson: function(name,age){
if(!instance){
instance = init(name,age)
}
return instance
}
}
})()
console.log(Person2.createPerson('hh',28))
console.log(Person2.createPerson('ll',28))
var Person3 = (function(){
var name = 'hh'
var age = 28
return {
name: name,
age: age,
sayName: function(){
return name
}
}
})()
console.log(Person3)
function Person4(name,age){
this.name = name
this.age = age
}
Person4.prototype = {
sayName: function(){
return this.name
}
}
function Student(name,age,score){
Person.call(this,name,age)
this.score = score
}
Student.prototype = Object.create(Person4.prototype)
Student.prototype.constructor = Student
Student.prototype.study = function(){
console.log('I am studying')
}
console.log(new Student('hh',28,100))
var EventCenter = (function(){
var events = {}
function on(eve,handler) {
events[eve] = events[eve] || []
events[eve].push(handler)
}
function trigger(eve,args){
if(!events[eve]) {return}
for (let i = 0;i < events[eve].length;i++){
events[eve][i](args)
}
}
function off(eve){
delete events[eve]
}
return {
on: on,
trigger: trigger,
off: off
}
})()
EventCenter.on('my_event', function(data){
console.log('my_event received...');
});
EventCenter.on('my_event', function(data){
console.log('my_event2 received...');
});
EventCenter.trigger('my_event');
2.使用发布订阅模式写一个事件管理器,可以实现如下方式调用
var Event = (function(){
var events = {}
function on(eve,handler) {
events[eve] = events[eve] || []
events[eve].push(handler)
}
function trigger(eve,args){
if(!events[eve]) {return}
for (let i = 0;i < events[eve].length;i++){
events[eve][i](args)
}
}
function off(eve){
delete events[eve]
}
return {
on: on,
trigger: trigger,
off: off
}
})()
Event.on('change', function(val){
console.log('change... now val is ' + val);
});
Event.fire('change', '饥人谷');
Event.off('change');