js设计模式

Constructor(构造器)模式

1
2
3
4
5
6
7
8
9
10
11
function Person(name, age) {
this.name = name;
this.age = age;
}

Person.prototype.sleep = function() {
return 'zzzzzzzzz';
};

let wangys219 = new Person('wangys219', 219);
console.log(wangys219.sleep());
  • sleep()在所有Person对象间共享

Module(模块)模式

js中实现模块的方法

  • 对象字面量
  • Module模式
  • AMD模块
  • CommonJS模块
  • ECMAScript Harmony模块

对象字面量

1
2
3
4
let someObjectLiteral = {
variableKey: variableValue,
functionKey: function () {},
};

Module模式

1
2
3
4
5
6
7
8
9
10
11
12
13
let someNamespace = (function () {
// 私有变量
let somePrivateVariableKey = variableValue;
// 私有方法
let somePrivateMethod = function () {};

return {
// 公有变量
somePublicVariableKey: variableValue,
// 公有方法
somePublicMethod: function () {},
};
})();

Module模式变化

引入混入

1
2
3
let someModule = (function (module1, module2...) {

})(module1, module2...);

优缺点

  • 优点
    • 支持私有成员
  • 缺点
    • 私有成员无法测试

Revealing Module(揭示模块)模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let someRevealingModule = (function () {
// 私有成员
let somePrivateVariableKey = somePrivateVariableValue;
// 私有方法
function somePrivateMethod () {}
// 公有成员
let somePublicVariableKey = somePublicVariableValue;
// 公有方法
function somePublicMethod () {}

return {
// 公有指针
publicCursor1: somePublicVariableKey,
publicCursor2: somePublicMethod,
};
})();

优缺点

  • 优点
    • 可读性高?

Singleton(单例)模式

1
2
3
4
5
6
7
8
9
10
11
12
13
let someSingleton = (function () {
let instance;

function init () {}

return {
getInstance: function () {
if (!instance) instance = init();

return instance;
},
};
})();

Observer(观察者)模式

  • Subject(目标): 维护一系列观察者,添加删除观察者
  • Observer(观察者): 为那些在目标状态发生改变时需获取通知的对象提供更新接口
  • ConcreteSubject(具体目标): 状态发生改变时,向Observer发出通知,储存ConcreteObserver的状态
  • ConcreteObserver(具体观察者):