js 设计模式-单例模式
本文参考:http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript
目录:
1)什么是单例
2)使用场景
3)类比
3)举例
什么是单例?
单例要求一个类有且只有一个实例,提供一个全局的访问点。因此它要绕过常规的控制器,使其只能有一个实例,供使用者使用,而使用着不关心有几个实例,因此这是设计者的责任
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:3, yy:4, 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 || 6; 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: 5 }); // Log the output of pointX just to verify it is correct // Outputs: 5 console.log( singletonTest.pointX ); |
欢迎大家拍砖!!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述