(25)设计模式之单例模式

介绍

从本章开始,我们会逐步介绍在JavaScript里使用的各种设计模式实现,在这里我不会过多地介绍模式本身的理论,而只会关注实现。OK,正式开始。

在传统开发工程师眼里,单例就是保证一个类只有一个实例,实现的方法一般是先判断实例存在与否,如果存在直接返回,如果不存在就创建了再返回,这就确保了一个类只有一个实例对象。在JavaScript里,单例作为一个命名空间提供者,从全局命名空间里提供一个唯一的访问点来访问该对象。

_6正文

在JavaScript里,实现单例的方式有很多种,其中最简单的一个方式是使用对象字面量的方法,其字面量里可以包含大量的属性和方法:

  1. var mySingleton = {
  2. property1: "something",
  3. property2: "something else",
  4. method1: function () {
  5. console.log('hello world');
  6. }
  7. };

如果以后要扩展该对象,你可以添加自己的私有成员和方法,然后使用闭包在其内部封装这些变量和函数声明。只暴露你想暴露的public成员和方法,样例代码如下:

  1. var mySingleton = function () {
  2. /* 这里声明私有变量和方法 */
  3. var privateVariable = 'something private';
  4. function showPrivate() {
  5. console.log(privateVariable);
  6. }
  7. /* 公有变量和方法(可以访问私有变量和方法) */
  8. return {
  9. publicMethod: function () {
  10. showPrivate();
  11. },
  12. publicVar: 'the public can see this!'
  13. };
  14. };
  15. var single = mySingleton();
  16. single.publicMethod(); // 输出 'something private'
  17. console.log(single.publicVar); // 输出 'the public can see this!'

上面的代码很不错了,但如果我们想做到只有在使用的时候才初始化,那该如何做呢?为了节约资源的目的,我们可以另外一个构造函数里来初始化这些代码,如下:

  1. var Singleton = (function () {
  2. var instantiated;
  3. function init() {
  4. /*这里定义单例代码*/
  5. return {
  6. publicMethod: function () {
  7. console.log('hello world');
  8. },
  9. publicProperty: 'test'
  10. };
  11. }
  12. return {
  13. getInstance: function () {
  14. if (!instantiated) {
  15. instantiated = init();
  16. }
  17. return instantiated;
  18. }
  19. };
  20. })();
  21. /*调用公有的方法来获取实例:*/
  22. Singleton.getInstance().publicMethod();

知道了单例如何实现了,但单例用在什么样的场景比较好呢?其实单例一般是用在系统间各种模式的通信协调上,下面的代码是一个单例的最佳实践:

  1. var SingletonTester = (function () {
  2. //参数:传递给单例的一个参数集合
  3. function Singleton(args) {
  4. //设置args变量为接收的参数或者为空(如果没有提供的话)
  5. var args = args || {};
  6. //设置name参数
  7. this.name = 'SingletonTester';
  8. //设置pointX的值
  9. this.pointX = args.pointX || 6; //从接收的参数里获取,或者设置为默认值
  10. //设置pointY的值
  11. this.pointY = args.pointY || 10;
  12. }
  13. //实例容器
  14. var instance;
  15. var _static = {
  16. name: 'SingletonTester',
  17. //获取实例的方法
  18. //返回Singleton的实例
  19. getInstance: function (args) {
  20. if (instance === undefined) {
  21. instance = new Singleton(args);
  22. }
  23. return instance;
  24. }
  25. };
  26. return _static;
  27. })();
  28. var singletonTest = SingletonTester.getInstance({ pointX: 5 });
  29. console.log(singletonTest.pointX); // 输出 5

_115其它实现方式

1_117方法1:

  1. function Universe() {
  2. // 判断是否存在实例
  3. if (typeof Universe.instance === 'object') {
  4. return Universe.instance;
  5. }
  6. // 其它内容
  7. this.start_time = 0;
  8. this.bang = "Big";
  9. // 缓存
  10. Universe.instance = this;
  11. // 隐式返回this
  12. }
  13. // 测试
  14. var uni = new Universe();
  15. var uni2 = new Universe();
  16. console.log(uni === uni2); // true

2_143方法2:

  1. function Universe() {
  2. // 缓存的实例
  3. var instance = this;
  4. // 其它内容
  5. this.start_time = 0;
  6. this.bang = "Big";
  7. // 重写构造函数
  8. Universe = function () {
  9. return instance;
  10. };
  11. }
  12. // 测试
  13. var uni = new Universe();
  14. var uni2 = new Universe();
  15. uni.bang = "123";
  16. console.log(uni === uni2); // true
  17. console.log(uni2.bang); // 123

3_169方法3:

  1. function Universe() {
  2. // 缓存实例
  3. var instance;
  4. // 重新构造函数
  5. Universe = function Universe() {
  6. return instance;
  7. };
  8. // 后期处理原型属性
  9. Universe.prototype = this;
  10. // 实例
  11. instance = new Universe();
  12. // 重设构造函数指针
  13. instance.constructor = Universe;
  14. // 其它功能
  15. instance.start_time = 0;
  16. instance.bang = "Big";
  17. return instance;
  18. }
  19. // 测试
  20. var uni = new Universe();
  21. var uni2 = new Universe();
  22. console.log(uni === uni2); // true
  23. // 添加原型属性
  24. Universe.prototype.nothing = true;
  25. var uni = new Universe();
  26. Universe.prototype.everything = true;
  27. var uni2 = new Universe();
  28. console.log(uni.nothing); // true
  29. console.log(uni2.nothing); // true
  30. console.log(uni.everything); // true
  31. console.log(uni2.everything); // true
  32. console.log(uni.constructor === Universe); // true

4_219方式4:

  1. var Universe;
  2. (function () {
  3. var instance;
  4. Universe = function Universe() {
  5. if (instance) {
  6. return instance;
  7. }
  8. instance = this;
  9. // 其它内容
  10. this.start_time = 0;
  11. this.bang = "Big";
  12. };
  13. } ());
  14. //测试代码
  15. var a = new Universe();
  16. var b = new Universe();
  17. alert(a === b); // true
  18. a.bang = "123";
  19. alert(b.bang); // 123

_250参考资料

https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/singleton.html

http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript