zoukankan      html  css  js  c++  java
  • 设计模式之单例模式,学习笔记

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

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

  • 相关阅读:
    Java数据库操作(MySQL与SQLserver)
    LeetCode 11. 盛最多水的容器
    LeetCode 10.正则表达式匹配
    LeetCode 9.回文数
    LeetCode 7. 整数反转
    LeetCode 6.Z 字形变换
    LeetCode 4.寻找两个正序数组的中位数
    LeetCode 3. 无重复字符的最长子串
    JOI2020遗迹
    线性规划对偶
  • 原文地址:https://www.cnblogs.com/pssp/p/5793106.html
Copyright © 2011-2022 走看看