javascript设计模式--单例模式

javascript单例模式总结javascript

1.什么是单例模式?html

单例模式的定义是:一个类仅有一个实例,而且能够在全局访问
在平常开发中,单例模式的使用十分普遍。例如开发登陆浮窗,咱们不管点击登陆按钮多少次,浮窗都只会建立一次。
这时,浮窗就很适合使用单例模式来建立。java

2.实现单例模式设计模式

var CreatePopbox = function(html){
    this.html = html;
    this._init();
};

CreatePopbox.prototype._init = function(){
    this.div = document.createElement('div');
    this.div.innerHTML = this.html;
    this.div.style.display = 'none';
    document.body.appendChild(this.div);

};

CreatePopbox.prototype.show = function(){
    this.div.style.display = 'block';
};

CreatePopbox.prototype.hide = function(){
    this.div.style.display = 'none';
};

//经过代理函数达到单例模式的效果

var proxysingleCreatePopbox = (function(){
    var instance;
    return function(html){
        if(!instance){
            instance = new CreatePopbox(html);
        }
        return instance;
    }
})();


//建立CreatePopbox:

var a = new proxysingleCreatePopbox("this is a");
var b = new proxysingleCreatePopbox("this is b");

console.log(a === b);  //true

能够看到,a和b都指向了同一个实例,执行new proxysingleCreatePopbox("this is b") 时,并不会从新生成一个新的CreatePopbox
这符合了单例模式的核心:确保实例只有一个app

经过以上例子,咱们已经了解单例模式的实现方式,但还有一些缺陷:ide

建立对象和单例管理的逻辑都合在proxysingleCreatePopbox里边,当须要建立其余单例时,只能把proxysingleCreatePopbox拷贝一次。函数

所以,咱们须要把代码再改造一下,把不变的部分隔离出来。this

//
var getSingle = function(fn){
  var singleObj;
  return function(obj){
    if(!singleObj){
      singleObj = new fn(obj);
    }
    return singleObj;
  }
}



var CreatePopbox = function(opation){
  this.html = opation.html;
  this._init();
};

CreatePopbox.prototype._init = function(){
  this.div = document.createElement('div');
  this.div.innerHTML = this.html;
  document.body.appendChild(this.div);
};

var singlePopbox = getSingle(CreatePopbox);

var a = new singlePopbox({html:"this is a"});

//建立一个新的单例

var CreateTipbox = function(opation){
  this.div = document.createElement('div');
  this.div.style.color = opation.color;
  this.div.innerHTML = opation.html;
  document.body.appendChild(this.div);
} 

//使用getSingle管理
var singleTipbox = getSingle(CreateTipbox);
var b = new singleTipbox({html:"this is b",color:"#f00"});

原文连接:javascript设计模式--单例模式prototype

相关文章
相关标签/搜索