设计模式之单例模式,学习笔记

所谓的单例模式就是说一个对象,我们只去实例化一次,在页面中如果有一个对象是唯一的,那么就可以用单例模式。

var Fn = function(name){
  this.name = name;
};

Fn.prototype.getName = function(){
  return this.name;
};

Fn.getInstrace = (function(){
  var isNew = null;
  return function(name){
    return isNew || (isNew = new Fn(name));
  };
}());


var a = Fn.getInstrace('JS');
console.log(a.name); //JS
var b = Fn.getInstrace('JSSssss');
console.log(b.name); //JS
console.log(a===b); //true

因为只需要实例化一次所以后面传的参数是没有用的。

var createDiv = function(html){
  this.html = html;
  this.init();
};
createDiv.prototype.init = function(){
  var div = document.createElement('div');
  div.innerHTML = this.html;
  document.body.appendChild(div);
};

var dan = (function(){
  var is = null;
  return function(html){
    if(!is){
      return is = new createDiv(html);
    }
  return is;
};
}());

var a = new dan('啊啊啊啊啊啊');
var b = new dan('啊啊啊啊啊啊111');
console.log(a===b);

原文地址:https://www.cnblogs.com/smallroc/p/6593364.html