javascript设计模式——Singleton
2024-08-29 09:21:54
单例模式指的是只能被实例化一次。
推荐阅读:
http://blog.mgechev.com/2014/04/16/singleton-in-javascript/
比较通用的一种Singleton模式
var mySingleton = (function () {
// Instance stores a reference to the Singleton
var instance;
function init() {
// Singleton
// Private methods and variables
function privateMethod(){
console.log( "I am private" );
}
var privateVariable = "Im also private";
var privateRandomNumber = Math.random();
return {
// Public methods and variables
publicMethod: function () {
console.log( "The public can see me!" );
},
publicProperty: "I am also public",
getRandomNumber: function() {
return privateRandomNumber;
}
};
};
return {
// Get the Singleton instance if one exists
// or create one if it doesn't
getInstance: function () {
if ( !instance ) {
instance = init();
}
return instance;
}
};
})();
var singleA = mySingleton.getInstance();
var singleB = mySingleton.getInstance();
console.log( singleA === singleB); // true
这种写法的好处有
1.只能实例化一次
2.可以存在私有函数
3.变量不可访问,不容易被修改。
最新文章
- 0x00linux32位汇编初入--前期准备
- python 线程编程
- php——用for循环打印半金字塔、金字塔、正方形、倒金字塔、菱形、空心图形等
- Thrift 个人实战--Thrift 网络服务模型
- POI对Excel
- J2EE 第二阶段项目(八)
- Hadoop中的辅助类ToolRunner和Configured的用法详解
- Oracle DB 使用调度程序自动执行任务
- AutoCAD.NET二次开发:创建自定义菜单(COM)
- Android版本控制系统及其间的差异
- Eclipse servlet和jsp编写
- html5学习(一) video字段
- 029_mount bind挂载
- Torchvision 源码安装[Ubuntu]
- freckles
- TCP_NODELAY算法使用事项
- Python oct() 函数
- PHP MemCached高级缓存配置图文教程
- gopherjs
- 由于link顺序错误导致的undefined reference