前端常见设计模式
2017-11-25 本文已影响0人
Gia_Mo
1. 写出 构造函数模式、混合模式、模块模式、工厂模式、单例模式、发布订阅模式的范例。
- 构造函数模式
<script>
function Car(name, year, country){
this.name = name;
this.year = year;
this.country = country;
}
Car.prototype.sayName = function(){
return this.name;
}
var mycar = new Car("BMW", 2017, "Germany");
console.log(mycar);
</script>
- 混合模式
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
console.log(this.name)
}
function Student(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 supo = new Student("supo", 20, 80)
supo.sayName();
supo.sayScore();
- 模块模式
/*
模块模式
- JS的模块通过作用域体现
- 一个模块代表一个作用域
- 词法作用域:
- 一个Fn能访问的上下文空间
- 有它所定义的位置决定
- 可通过闭包实现
- 不会污染全局
*/
var Person = (function() {
var name = 'xxx'
function sayName() {
console.log(name)
}
return{
name: name,
sayName: sayName
}
})()
- 工厂模式
<script>
function Car(name, year, country){
var obj = new Object();
obj.name = name;
obj.year = year;
obj.country = country;
obj.sayName = function(){
console.log(this.name);
}
return obj
}
var mycar = Car("BMW", 2017, "Germany");
var yourcar = Car("Benz", 2016, "Germany");
</script>
- 单例模式
var Car = (function(){
var car;
function init(name, year, country) {
return {
name: name,
year: year,
country: country
}
}
return {
createCar: function(name, year, country){
if(!car){
car = init(name, year, country);
}
return car;
}
}
}());
var car1 = Car.createCar("BMW", 2017, "Germany");
var car2 = Car.createCar("Benz", 2016, "Germany");
- 发布订阅模式
var EventCenter = (function(){
var events = {};
function on(event, handler){
events[event] = events[event] || [];
events[event].push({
handler: handler
});
}
function fire(event, args){
if (!events[event]) {return}
for (var i = 0; i < events[event].length; i++) {
events[event][i].handler(args);
}
}
function off(event){
delete events[event];
}
return {
on: on,
fire: fire,
off: off
}
})();
EventCenter.on('event', function(data){
console.log('event received...');
});
EventCenter.on('event', function(data){
console.log('event2 received...');
});
EventCenter.fire('event');
EventCenter.off('event');
EventCenter.fire('event');
2. 使用发布订阅模式写一个事件管理器,可以实现如下方式调用
Event.on('change', function(val){
console.log('change... now val is ' + val);
});
Event.fire('change', '饥人谷');
Event.off('change');
var Event = (function(){
var events = {};
function on(event, handler){
events[event] = events[event] || [];
events[event].push({
handler: handler
})
};
function fire(event, args){
if (!events[event]) {
return
}
for (var i = 0; i < events[event].length; i++) {
events[event][i].handler(args)
}
}
function off(event){
delete events[event]
}
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');
Event.fire('change', '饥人谷');