Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

简单的总结Js的单例模式 #7

Open
aototo opened this issue May 26, 2017 · 0 comments
Open

简单的总结Js的单例模式 #7

aototo opened this issue May 26, 2017 · 0 comments

Comments

@aototo
Copy link
Owner

aototo commented May 26, 2017

简单的总结Js的单例模式

单例模式

单例模式的类必须保证只有一个实例存在。许多时候整个系统只需要拥有一个的全局对象,这样有利于我们协调系统整体的行为

但是Js里面不存在类,所以实现单例模式跟传统语言并非要一样(需要创建一个类)。

  1. 可以使用对象字面量的方法, (ps: 这本质上并非单例模式, 但能提供所要的需求)

     var Singleton = {
       method: function () {
     	  console.log('hello');
       }
     };
    
  2. 惰性单例
    页面需要一个唯一的弹窗的时候,并且使用的时候才初始化,减少没必要的性能开销。如下例子:

    var createSingleDiv = (function() {
    		var div;
    		createSingleDiv = function() {
    		    if (!div) {
    			    div = document.createElement('div');
    			    div.innerHTML = "弹窗";
    				document.body.appendChild(div);
    				
    				return div;
    		    }
    		 }
    		 
    		return createSingleDiv
    })();
    
    button.onclick = function() {
      createSingleDiv();
    }

    当点击button的时候我们去初始化创建div,这样就可以减少一开始就创建node节点造成的性能开销,因为有时候用户并非要点击。

  3. 内部new实例
    下面的例子用在系统间各种模式的通信协调上。

    var Singleton = (function () {
        function Singleton(args) {
            var args = args || {};
            this.args = args;
        }
    
        //实例容器
        var instance;
    
        var _static = {
            //返回Singleton的实例
            getInstance: function (args) {
                if (instance === undefined) {
                    instance = new Singleton(args);
                }
                return instance;
            }
        };
    
        return _static;
    })();
    
    var singleton = Singleton.getInstance({name: "app"});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant