首页 > 其他 > 详细

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

时间:2016-08-21 18:33:38      阅读:232      评论:0      收藏:0      [点我收藏+]

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

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);

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

原文:http://www.cnblogs.com/pssp/p/5793106.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!