gpt4 book ai didi

singleton - 对于带参数的构造函数,goog.addSingletonGetter() 是否有变体?

转载 作者:行者123 更新时间:2023-12-04 05:37:34 25 4
gpt4 key购买 nike

我想用goog.addSingletonGetter() ( http://closure-library.googlecode.com/svn/!svn/bc/4/trunk/closure/goog/docs/closure_goog_testing_singleton.js.source.html#line56 ) 添加 getInstance()具有接受参数的构造函数的类的方法:

Foo = function(x, y) {...};

有没有办法让我指定 goog.addSingletonGetter(Foo, arg1, arg2) ?调用 Foo.getInstance()然后会懒洋洋地返回实例化的 Foo 对象。

最佳答案

Closure: The Definitive Guide 第 70 页定义 goog.addSingletonGetter()如下:

For a class with a constructor that takes zero arguments, goog.addSingletonGetter() adds a static method to its constructor function named getInstance() that returns the same instance of that object whenever it is called. Generally, it should be used instead of the constructor function if it exists.



一种方法是在 之后创建一个单例。静态属性中的实例 设计模式呈现于 JavaScript Patterns 在第 143 页添加了静态 getInstance()功能。

/**
* @param {string=} opt_x
* @param {string=} opt_y
* @constructor
*/
Foo = function(opt_x, opt_y) {

if(Foo.instance_) {
return Foo.instance_;
}

/**
* @type {string}
* @private
*/
this.x_ = goog.isDefAndNotNull(opt_x) ? opt_x : 'default_X';

/**
* @type {string}
* @private
*/
this.y_ = goog.isDefAndNotNull(opt_y) ? opt_y : 'default_Y';

Foo.instance_ = this;
};


/**
* Get the singleton instance of Foo.
* @param {string=} opt_x
* @param {string=} opt_y
*/
Foo.getInstance = function(opt_x, opt_y) {
if (Foo.instance_) {
return Foo.instance_;
}
return new Foo(opt_x, opt_y);
};

使用此模式的优势在于,它可以防止您在有人编写以下内容时意外构建多个实例:

var foo = new Foo();

...
// thousands of lines later
var snafoo = new Foo(); // Returns the singleton instance.

关于singleton - 对于带参数的构造函数,goog.addSingletonGetter() 是否有变体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11730384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com