js单例模式详解实例
什么是单例?
单例要求一个类有且只有一个实例,提供一个全局的访问点。因此它要绕过常规的控制器,使其只能有一个实例,供使用者使用,而使用着不关心有几个实例,因此这是设计者的责任
In JavaScript, Singletons serve as a shared resource namespace which isolate implementation code from the global namespace so as to provide a single point of access for functions.
在javascript中,单例被当做一个全局的命名空间,提供一个访问该对象的一个点。
使用场景
In practice, the Singleton pattern is useful when exactly one object is needed to coordinate others across a system.
单例比较适用于一个对象和其他系统进行交互。
类比
单例有点类似于一个小组的小组长,在一段时间内只有一个小组长,有小组长来指定组员的工作,分配和协调和组员的工作。
实例1:这个是最简单的单例,通过key,value的形式存储属性和方法
var A = {
xx:,
yy:,
B:function(el){
},
C:function(el){
},
D:function(el){
},
E:function(el){
}
}
实例2:首先创建一个实例的引用,然后判断这个实例是否存在,如果不存在那么就创建,存在的话,就直接返回,保证有且只有一个。
var mySingleton = (function () {
// Instance 存储一个单例实例的引用
var instance;
function init() {
// Singleton
// 私有的方法和变量
function privateMethod(){
console.log( "I am private" );
}
var privateVariable = "Im also private";
return {
// 共有的方法和变量
publicMethod: function () {
console.log( "The public can see me!" );
},
publicProperty: "I am also public"
};
};
return {
// 如果实例不存在,那么创建一个
getInstance: function () {
if ( !instance ) {
instance = init();
}
return instance;
}
};
})();
var singleA = mySingleton;
var singleB = mySingleton;
console.log( singleA === singleB ); // true
实例3:
var SingletonTester = (function () {
// options: an object containing configuration options for the singleton
// e.g var options = { name: "test", pointX: 5};
function Singleton( options ) {
// set options to the options supplied
// or an empty object if none are provided
options = options || {};
// set some properties for our singleton
this.name = "SingletonTester";
this.pointX = options.pointX || ;
this.pointY = options.pointY || ;
}
// our instance holder
var instance;
// an emulation of static variables and methods
var _static = {
name: "SingletonTester",
// Method for getting an instance. It returns
// a singleton instance of a singleton object
getInstance: function( options ) {
if( instance === undefined ) {
instance = new Singleton( options );
}
return instance;
}
};
return _static;
})();
var singletonTest = SingletonTester.getInstance({
pointX:
});
// Log the output of pointX just to verify it is correct
// Outputs: 5
console.log( singletonTest.pointX );
单例模式
- var single = (function(){
- var unique;
- function getInstance(){
- if( unique === undefined ){
- unique = new Construct();
- }
- return unique;
- }
- function Construct(){
- // ... 生成单例的构造函数的代码
- }
- return {
- getInstance : getInstance
- }
- })();
实现1: 最简单的对象字面量
- var singleton = {
- attr : 1,
- method : function(){ return this.attr; }
- }
- var t1 = singleton ;
- var t2 = singleton ;
实现2:构造函数内部判断
- function Construct(){
- // 确保只有单例
- if( Construct.unique !== undefined ){
- return Construct.unique;
- }
- // 其他代码
- this.name = "NYF";
- this.age="24";
- Construct.unique = this;
- }
- var t1 = new Construct() ;
- var t2 = new Construct() ;
实现3 : 闭包方式
- var single = (function(){
- var unique;
- function Construct(){
- // ... 生成单例的构造函数的代码
- }
- unique = new Constuct();
- return unique;
- })();
总结
js单例模式详解实例的更多相关文章
- js对象详解(JavaScript对象深度剖析,深度理解js对象)
js对象详解(JavaScript对象深度剖析,深度理解js对象) 这算是酝酿很久的一篇文章了. JavaScript作为一个基于对象(没有类的概念)的语言,从入门到精通到放弃一直会被对象这个问题围绕 ...
- 9种Java单例模式详解(推荐)
单例模式的特点 一个类只允许产生一个实例化对象. 单例类构造方法私有化,不允许外部创建对象. 单例类向外提供静态方法,调用方法返回内部创建的实例化对象. 懒汉式(线程不安全) 其主要表现在单例类在外 ...
- Message,MessageQueue,Looper,Handler详解+实例
Message,MessageQueue,Looper,Handler详解+实例 原文地址 Android的Handler使用(这篇简单介绍Handler的使用) 一.几个关键概念 1.Message ...
- iOS开发——UI篇OC篇&UICollectionView详解+实例
UICollectionView详解+实例 实现步骤: 一.新建两个类 1.继承自UIScrollView的子类,比如HMWaterflowView * 瀑布流显示控件,用来显示所有的瀑布流数据 2. ...
- Android:weight,margin,padding详解实例
weight详解 weight是用来等比例划分区域的属性. 案例代码 <LinearLayout xmlns:android="http://schemas.android.com/a ...
- 常用经典SQL语句大全完整版--详解+实例 (存)
常用经典SQL语句大全完整版--详解+实例 转 傻豆儿的博客 http://blog.sina.com.cn/shadou2012 http://blog.sina.com.cn/s/blog_84 ...
- iOS之UI--使用SWRevealViewController 实现侧边菜单功能详解实例
iOS之UI--使用SWRevealViewController 实现侧边菜单功能详解实例 使用SWRevealViewController实现侧边菜单功能详解 下面通过两种方法详解SWReveal ...
- gvoory脚本中关于HttpClient使用详解实例
一.gvoory脚本中关于HttpClient使用详解实例 HttpClient:是一个接口 首先需要先创建一个DefaultHttpClient的实例 HttpClient httpClient=n ...
- 常用经典SQL语句大全完整版--详解+实例 《来自网络,很全没整理,寄存与此》
常用经典SQL语句大全完整版--详解+实例 下列语句部分是Mssql语句,不可以在access中使用. SQL分类: DDL—数据定义语言(CREATE,ALTER,DROP,DECLARE) DML ...
随机推荐
- ZOJ 3469 Food Delivery(区间DP好题)
题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=4255 题目大意:在x轴上有n个客人,每个客人每分钟增加的愤怒值不同. ...
- JS中精选this关键字的指向规律你记住了吗
1.首先要明确: 谁最终调用函数,this指向谁 this指向的永远只可能是对象!!!!! this指向谁永远不取决于this写在哪,而取 ...
- python中mock的使用
什么是mock? mock在翻译过来有模拟的意思.这里要介绍的mock是辅助单元测试的一个模块.它允许您用模拟对象替换您的系统的部分,并对它们已使用的方式进行断言. 在Python2.x 中 mock ...
- CF 586A 找1的个数和101的个数
Sample test(s) input 50 1 0 1 1 output 4 input 71 0 1 0 0 1 0 output 4 input 10 output 0 # include & ...
- 安装配置SVN
官网下载地址,下载完之后如果想看到中文,可以下载语言包进行安装,安装之后TortoiseSVN -> Settings -> General -> Language选项中选择:中文( ...
- day6 SYS模块
SYS模块 用于提供对Python解释器相关的操作: (1)sys.argv 命令行参数List,第一个元素是程序本身路径 >>> sys.argv [' ...
- 004 Hadoop2.x基础知识
一:大数据应用 1.Cloudera cloudera公司是Hadoop三大发行商之一,其版本为CDH版本,现在最新的版本是CDH5. 网站:http://archive.cloudera.com/c ...
- hdoj2191 珍惜现在,感恩生活(01背包 || 多重背包)
题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=2191 思路 由于每种大米可能不止一袋,所以是多重背包问题,可以直接使用解决多重背包问题的方法,也可以将 ...
- Two-stage rotation animation is deprecated. This application should use the smoother single-stage an
问题出在rootViewController同时包含UITabBarController和UINavigationController. 几经尝试,最后发现,在设置为window.rootViewCo ...
- mysql 函数group_concat()
本文通过实例介绍了MySQL中的group_concat函数的使用方法,比如select group_concat(name) .MySQL中group_concat函数完整的语法如下:group_c ...