用JavaScript实现单例模式的最简单/最干净的方法是什么?
当前回答
如果你正在使用node.JS,那么你可以利用node.JS的缓存机制,你的单例将像这样简单:
class Singleton {
constructor() {
this.message = 'I am an instance';
}
}
module.exports = new Singleton();
请注意,我们导出的不是类Singleton,而是实例Singleton()。
Node.JS将在每次需要时缓存和重用相同的对象。
更多细节请查看:Node.JS和单例模式
其他回答
我需要几个单人间:
延迟初始化 初始参数
这就是我想到的:
createSingleton ('a', 'add', [1, 2]);
console.log(a);
function createSingleton (name, construct, args) {
window[name] = {};
window[construct].apply(window[name], args);
window[construct] = null;
}
function add (a, b) {
this.a = a;
this.b = b;
this.sum = a + b;
}
args必须是Array,所以如果你有空变量,只需要传入[] 我在函数中使用了window对象,但我本可以传入一个参数来创建自己的作用域 name和构造参数只是字符串,以便window[]工作,但有一些简单的类型检查,window.name和window.name。构造也是可能的。
你没说"在浏览器里"否则,你可以使用Node.js模块。这些对于每个require调用都是相同的。基本的例子:
foo.js的内容: Const circle = require('./circle.js'); console.log('半径为4的圆的面积为${circle.area(4)} '); circle.js的内容: const PI = Math.PI; 出口。area = (r) => PI * r * r; 出口。周长= (r) => 2 * PI * r;
注意,您不能访问圆。PI,因为它没有导出。
虽然这在浏览器中不起作用,但它简单而干净。
var singleton = (function () {
var singleton = function(){
// Do stuff
}
var instance = new singleton();
return function(){
return instance;
}
})();
一个没有getInstance方法的解决方案。
我从JavaScript模式中得到了这个例子 用编码和设计模式构建更好的应用程序一书(Stoyan Stefanov著)。如果你需要一些简单的实现类,比如单例对象,你可以使用一个直接函数,如下所示:
var ClassName;
(function() {
var instance;
ClassName = function ClassName() {
// If the private instance variable is already initialized, return a reference
if(instance) {
return instance;
}
// If the instance is not created, save a pointer of the original reference
// to the private instance variable.
instance = this;
// All constructor initialization will be here
// i.e.:
this.someProperty = 0;
this.someMethod = function() {
// Some action here
};
};
}());
你可以通过下面的测试用例来检查这个例子:
// Extending defined class like singleton object using the new prototype property
ClassName.prototype.nothing = true;
var obj_1 = new ClassName();
// Extending the defined class like a singleton object using the new prototype property
ClassName.prototype.everything = true;
var obj_2 = new ClassName();
// Testing makes these two objects point to the same instance
console.log(obj_1 === obj_2); // Result is true, and it points to the same instance object
// All prototype properties work
// no matter when they were defined
console.log(obj_1.nothing && obj_1.everything
&& obj_2.nothing && obj_2.everything); // Result true
// Values of properties which are defined inside of the constructor
console.log(obj_1.someProperty); // Outputs 0
console.log(obj_2.someProperty); // Outputs 0
// Changing property value
obj_1.someProperty = 1;
console.log(obj_1.someProperty); // Output 1
console.log(obj_2.someProperty); // Output 1
console.log(obj_1.constructor === ClassName); // Output true
这种方法通过了所有测试用例,而当使用原型扩展时,私有静态实现将失败(它可以被修复,但并不简单),而公共静态实现则不太可取,因为实例是公开给公众的。
jsFiddly demo.
对我来说,最简单/最干净的也意味着简单地理解,没有花哨的东西,就像Java版本的讨论中讨论的那样:
在Java中实现单例模式的有效方法是什么?
从我的角度来看,最简单/最干净的答案是:
Jonathan的回答是:在Java中实现单例模式的有效方法是什么?
它只能部分地翻译成JavaScript。JavaScript中的一些区别是:
构造函数不能是私有的 类不能有声明的字段
但考虑到最新的ECMA语法,有可能接近:
作为JavaScript类示例的单例模式
class Singleton {
constructor(field1,field2) {
this.field1=field1;
this.field2=field2;
Singleton.instance=this;
}
static getInstance() {
if (!Singleton.instance) {
Singleton.instance=new Singleton('DefaultField1','DefaultField2');
}
return Singleton.instance;
}
}
示例使用
console.log(Singleton.getInstance().field1);
console.log(Singleton.getInstance().field2);
例子的结果
DefaultField1
DefaultField2
推荐文章
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 在哪里放置AutoMapper.CreateMaps?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- 在Bash中传递带有空格的字符串作为函数参数
- ES6/2015中的null安全属性访问(和条件赋值)
- 在R函数中指定可选参数的“正确”方法
- 使用Enum实现单例(Java)
- 与push()相反;
- JS字符串“+”vs concat方法