zoukankan      html  css  js  c++  java
  • 【JavaScript设计模式】 单例模式

    <script type="text/javascript">
    	var Singleton = function() {
    		var _instance = null;
    		
    		return {
    			getInstance : function() {
    				if (!_instance) {
    					_instance = ['a', 'b', 'c', 'd'];
    				}
    
    				return _instance;
    			}
    		}
    	}();
    	
    	document.write(Singleton.getInstance());
    </script>

    保证只有一个实例对象,并且提供一个方法可让全局访问到此实例对象。

    一些应用场景:

    某些JavaScript的UI组件中,需要获取页面的DOM对象,只需要调用getInstance方法时返回该实例(调用时才判断是否已被初始化)的引用即可。

    实际中的应用如一个Dialog框:alert型、confirm型、loading型、login型..,可能只在需要创建一次容器(为避免频繁对DOM树的修改引发DOM的reflow而导致的消耗系统资源或是产生内存泄露)

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
     <head>
      <title>单例模式</title>
      <meta name="generator" content="editplus" />
      <meta name="author" content="meteoric_cry" />
      <meta name="keywords" content="" />
      <meta name="description" content="" />
      <meta http-equiv='content-type' content='text/html;charset=utf-8' />
      <style type='text/css'>
    	.tip {
    		background-color:#68af02;padding:5px 14px;color:#fff; font-size:14px;position:absolute;
    	}
      </style>
     </head>
    
     <body>
      
    <button onclick="Dialog.getInstance().update('111111');">显示框</button>&nbsp;&nbsp;
    <button onclick="Dialog.getInstance().update('内容已被修改');">修改内容</button>
    
    <script type="text/javascript">
    	var Dialog = function() {
    		var inner;
    		
    		var _instance = null;
    	
    		return inner = {
    			getInstance : function() {
    				if (!_instance) {
    					_instance = document.createElement("div");
    					_instance.className = "tip";
    					document.body.appendChild(_instance);
    				}
    
    				return inner;
    			},
    			update : function(str) {
    				_instance.innerHTML = str;
    			}
    		}
    	}();
    	
    </script>
    
     </body>
    </html>
  • 相关阅读:
    《Windows核心编程系列》十四谈谈默认堆和自定义堆
    《windows核心编程系列》十五谈谈windows线程栈
    《Windows核心编程系列》十三谈谈在应用程序中使用虚拟内存
    《Windows核心编程系列》十二谈谈Windows内存体系结构
    《Windows核心编程系列》十一谈谈Windows线程池
    Extjs利用vtype验证表单
    Extjs文本输入框
    Extjs文本输入域
    远程数据源Combobox
    Extjs整体加载树节点
  • 原文地址:https://www.cnblogs.com/meteoric_cry/p/1817166.html
Copyright © 2011-2022 走看看