javascript模式设计
2020-11-24 本文已影响0人
leleo
创建型设计模式:
- Constructor(构造器)模式
基本(Constructor)构造器
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.sayName = function () {
console.log(this.name);
}
}
var person1 = new Person('Nicholas', 29, 'Software Engineer');
var person2 = new Person('Greg', 27, 'Doctor');
弊端:继承变得困难,每一次new都重新定义了新对象,sayName() 没有实现共享。
带原型的(Constructor)构造器
function Person(option) {
this._init(option);
}
Person.prototype._init = function(option){
this.name = option.name;
this.age = option.age;
this.job = option.job;
}
Person.prototype.sayName = function () {
console.log(this.name);
}
var person1 = new Person({name:'Nicholas', age:29, job:'Software Engineer'});
console.log(person1)
- Factory(工厂)模式
function createPerson(name, age, job) {
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function () {
console.log(this.name);
}
return o;
}
var person1 = createPerson('Nicholas', 29, 'Software Engineer');
var person2 = createPerson('Greg', 27, 'Doctor');
工厂模式解决了创建多个相似的问题,却没有解决对象识别的问题(即怎样知道一个对象的类型)
- Prototype(原型)
function Person() {}
Person.prototype.name = 'Nicholas';
Person.prototype.age = 29;
Person.prototype.job = 'Software Engineer';
Person.prototype.sayName = function () {
console.log(this.name);
}
var person1 = new Person();
person1.sayName(); //'Nicholas'
var person2 = new Person();
person1.sayName(); // 'Nicholas'
- Builder(生成器)
- Singleton(单例)
单例模式就是保证一个类只有一个实例,实现的方法一般是先判断实例存在与否,如果存在直接返回,如果不存在就创建了在返回,这就确保了一个类只有一个实例对象。在javascript里,单例作为一个命名空间提供者,从全局命名空间里提供一个唯一的访问点俩访问该对象。
- 唯一性
- 全局访问
- Factory(工厂)
- Abstract(抽象)
结构型设计模式:
- Decorator(装饰着)
- Facade(外观)
- Flyweight(享元)
- Adapter(适配器)
- Proxy(代理)
行为设计模式
- Iterator(迭代器)
- Mediator(终结者)
- Observer(观察者)
- Visitor(访问者)
- 发布订阅模式
let _subscribe = (function () {
// 发布订阅
class Sub {
constructor() {
// 创建事件池,用来存储后期需要执行的方法
this.pond = [];
}
// 添加方法
add(func) {
// 去重
let flag = this.pond.some(item => {
return item === func;
});
!flag ? this.pond.push(func) : null;
}
// 移除方法
remove(func) {
let pond = this.pond;
for (let i = 0; i < pond.length; i++) {
let item = pond[i];
if (item === func) {
pond[i] = null;
break;
}
}
}
// 通知执行
fire(...args) {
let pond = this.pond;
for (let i = 0; i < pond.length; i++) {
let item = pond[i];
if(typeof item !== func){
pond.splice(i,1);
i--;
continue;
}
item.call(this,...args);
}
}
}
return function Subscribe(){
return new Sub();
}
})();
let pond = _subscribe();
document.querySelector('.submit').onclick = function(ev){
pond.fire();
}
let fn1 = function(ev){
console.log(1,ev)
}
pond.add(fn1);
pond.fire();