js设计模式之单例模式

废话不多说,直接上代码以供参考吧!

 1 var SingleInstanceTest = (function () {
 2   var _instance = null;    //  申明一个唯一的对象
 3   //  设置默认值
 4   var _default = { name: '无名氏',age: 18 };
 5   function SingleInstance(ops) {
 6     if (this instanceof SingleInstance) {   //  优化处理不使用new关键字的问题
 7       if(_instance == null){   // 每次实例化判断对象是否为空
 8         this._init(ops);
 9         return _instance = this;
10       }else{
11         _instance._init(ops);
12         return _instance;       
13       }
14     }else{
15       if (!_instance) {
16         _instance = new SingleInstance();
17         _instance._init(ops);
18         return _instance;
19       } else {
20         _instance._init(ops);
21         return _instance;
22       }
23     }
24   }
25 
26   SingleInstance.prototype._init = function (ops) {
27     //  如果传进来的数据为真,则复制给默认数据
28     for(var prop in ops){
29       if(ops[prop]){
30         _default[prop] = ops[prop];
31       }
32     }
33     //  如果传进来的数据不包含默认数据中的字段,则将默认数据中的字段填充进传进来的对象中
34     for(var prop in _default){
35       this[prop] = _default[prop];
36     }
37   }
38   return SingleInstance;
39 })()
40 
41 var i0 = SingleInstanceTest({ name: '王五' });
42 var i1 = new SingleInstanceTest({ name: '张三', age: 20 })
43 var i2 = new SingleInstanceTest({ name: '李四' })

 

 再举一个显示与影藏div功能的单例

var Popup = (function() {
  var div = document.createElement('div');
  document.body.appendChild(div);
  var _instance = null;     //  创建一个唯一的对象
  return function () {
    if (_instance == null){   //  每次实例化判断_instance是否为空
      _instance = new Object();

      _instance.hide = function () {
        div.style.display = 'none';
      }
      _instance.show = function () {
        div.style.display = 'block';
      }
    }
    return _instance;
  }
})()

 

posted on 2018-07-10 15:45  破风晓月  阅读(697)  评论(0编辑  收藏  举报

导航