标签: singleton

是scala.Singleton纯编译小说吗?

该Scala语言规范下§3.2.1说:

稳定类型是单例类型或声明为特征scala.Singleton的子类型的类型.

我scala.Singleton在源代码,ScalaDoc和二进制jar文件中都找不到.

尝试REPL导致:

scala> class Foo extends Singleton
<console>:9: error: illegal inheritance from final trait Singleton
       class Foo extends Singleton
                         ^
<console>:9: error: illegal inheritance; superclass Any
 is not a subclass of the superclass Object
 of the mixin trait ScalaObject
       class Foo extends Singleton
                 ^
Run Code Online (Sandbox Code Playgroud)

scala.Singelton生活在哪里,它的目的是什么?

singleton types specifications scala language-design

7
推荐指数
1
解决办法
529
查看次数

工业强度的n吨基类模板

我正在研究一个n吨基类模板.我还不担心懒惰,所以意图是:

确保一个类只有n个实例,并提供对它们的全局访问点.

到目前为止,这是我的代码:

template<typename Derived, size_t n = 1>
class n_ton_base                 // Singletons are the default
{
    static Derived instances[n + (n == 0)];
                              // Zerotons are supported, too
protected:

    // Prevent n_ton_base to be used outside of inheritance hierarchies
    n_ton_base() {} 

    // Prevent n_ton_base (and Derived classes) from being copied
    n_ton_base(const n_ton_base&) = delete;

public:
                   // Get first element by default, useful for Singletons
    template<size_t i = 0>
    static Derived& get_instance()
    {
        static_assert(i < n, "Time to …
Run Code Online (Sandbox Code Playgroud)

c++ singleton templates design-patterns c++11

7
推荐指数
2
解决办法
504
查看次数

Singleton模式析构函数C++

我有这个单身模式,它运行正常.但是当我用valgrind执行我的程序来检查内存泄漏时,似乎实例永远不会被破坏.

我的错误在哪里?

头

class Stopwords {   
    private:
        static Stopwords* instance;
        std::map<std::string,short> diccionario;

    private: 
    Stopwords();

    public:
        ~Stopwords();

    public:
    static Stopwords* getInstance();
    std::map<std::string,short> getMap();
};
Run Code Online (Sandbox Code Playgroud)

的.cpp

Stopwords* Stopwords::instance = NULL;

Stopwords::Stopwords() {
    diccionario = map<string,short>();

    char nombre_archivo[] = "stopwords/stopwords.txt";
    ifstream archivo;
    archivo.open(nombre_archivo);
    string stopword;
    while(getline(archivo,stopword,',')) {
    diccionario[stopword] = 1;
    }
    archivo.close();
}

Stopwords::~Stopwords() {
    delete instance;
}


Stopwords* Stopwords::getInstance() {

    if (instance == NULL) {
       instance = new Stopwords ();
    }
    return instance;
}

map<string,short> Stopwords::getMap(){
    return diccionario;
}
Run Code Online (Sandbox Code Playgroud)

它没有关系,但在初始化时,我从文件中读取了一堆单词,然后将它们保存在地图实例中.

谢谢

c++ singleton valgrind destructor

7
推荐指数
3
解决办法
2万
查看次数

Ruby Class Singleton常量存储在哪里?

我们假设我们有这个Ruby类:

class MyClass
  class << self
    MC_CONST = 30
  end
end 
Run Code Online (Sandbox Code Playgroud)

然后,让我们实例化MyClass并向对象的元类添加另一个常量:

m = MyClass.new
class << m
  OBJ_MC_CONST = 50
end
Run Code Online (Sandbox Code Playgroud)

对象单例常量没有问题:

m.singleton_class::OBJ_MC_CONST # => 50 <-- [OK]
m.singleton_class.constants.include? :OBJ_MC_CONST # => true <- [OK]
Run Code Online (Sandbox Code Playgroud)

但不完全是我对类单例常量的期望:

MyClass.singleton_class::MC_CONST # => 30 <-- [OK]
MyClass.singleton_class.const_get :MC_CONST # => 30 <-- [OK]
MyClass.singleton_class.constants.include? :MC_CONST # => false <-- [Why???]
Run Code Online (Sandbox Code Playgroud)

为什么在.constants类的元MyClass类上由方法返回的数组不包含:MC_CONST?我在这里错过了什么?

谢谢.


编辑1:毕竟这似乎是MRI 2.x中的一个错误.我已经向Ruby核心团队提出了一个新问题:https://bugs.ruby-lang.org/issues/9413来解决这个问题.

编辑2:这个错误显然已在https://bugs.ruby-lang.org/projects/ruby-trunk/repository/revisions/44628/diff/中修复

ruby singleton constants

7
推荐指数
1
解决办法
388
查看次数

具有参数的对象的单例类

我意识到我应该只有一个被称为一次StdSchedulerFactory运行的对象实例.到目前为止,我实例化了这样的对象

StdSchedulerFactory sf = new StdSchedulerFactory(properties);
Run Code Online (Sandbox Code Playgroud)

而属性是一个NameValueCollection.如何为此对象编写Singleton类,以便变量sf在整个程序中始终具有一个实例?

c# singleton design-patterns

7
推荐指数
1
解决办法
5557
查看次数

ExtJS:使用远程加载的单例值进行商店定义

我在试图弄清楚如何做到这一点时遇到了一些麻烦(如果可能的话).

我有一个使用parse.com来存储它的数据的应用程序,我希望每个用户拥有一个不同的parse.com帐户,因此他们的数据集不会相互交叉.所以我创建了一个单例(设置),用于存储用户的appId和apiKey,它们是由我管理的一般parse.com帐户加载的,包含每个用户的电子邮件,appId和apiKey,因此当他们登录应用程序时用户的appId和apiKey.

问题是我需要在我的商店的定义中使用这些设置appId和apiKey,因为我需要在标题中发送它们.我已经做了一些测试,试图在应用程序启动时设置我的单例的全局变量,但是在商店定义时,这些"全局变量"都是空的,因为应用尚未启动.

这是我的一些代码,所以我可以让自己更清楚,因为我知道这不是最容易理解的.

的application.js

Ext.define('Settings', {
    singleton: true,        
    appId: null,
    apiKey: null
});


Ext.define('MyApp.Application', {
    extend: 'Ext.app.Application',        
    name: 'MyApp',        
    stores: [],
    launch: function () {
        Ext.create('MyApp.store.Settings').load({
            params: {
                'where': '{"email": "useremail@gmail.com"}' //email is supposed to be a user input but for the sakes of testing I just made it static
            },
            callback: function(records){
                var s = records[0];
                Settings.appId = s.get('appId');
                Settings.apiKey = s.get('apiKey');
                Parse.initialize(Settings.appId, Settings.apiKey);
            }
        });
    },


    onAppUpdate: function () {
        Ext.Msg.confirm('Application Update', 'This application has an update, …
Run Code Online (Sandbox Code Playgroud)

javascript singleton extjs store parse-platform

7
推荐指数
1
解决办法
693
查看次数

@Configuration是单例吗

我正在做我的日常工作,我意识到尽管我经常使用@Configuration,但我不知道它到底是如何工作的,在阅读了 spring.io 文档后,我无法确定 @Configuration 是否是一种制作单例类。

\n\n

所以......我想我的问题是:

\n\n

我应该使用什么来正确创建单例 @Configuration 或 @Component?这是为什么'?

\n\n

我一直在研究这两个选项,并举了两个这样的例子:

\n\n

第一个例子

\n\n
@Configuration\npublic static class Config {\n\n    @Bean\n    public SimpleBean simpleBean() {\n        return new SimpleBean();\n    }\n\n    @Bean\n    public SimpleBeanConsumer simpleBeanConsumer() {\n        return new SimpleBeanConsumer(simpleBean());\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

第二个例子

\n\n
@Component\npublic static class Config {\n\n    @Bean\n    public SimpleBean simpleBean() {\n        return new SimpleBean();\n    }\n\n    @Bean\n    public SimpleBeanConsumer simpleBeanConsumer() {\n        return new SimpleBeanConsumer(simpleBean());\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

第一段代码工作正常,并且正如预期的那样,SimpleBeanConsumer 将获得指向单例 SimpleBean 的链接。但不幸的是,它不能在签名环境中工作。

\n\n

第二种配置是完全不正确的,因为spring会创建一个SimpleBean的单例bean,但是SimpleBeanConsumer会获得另一个不受spring上下文控制的SimpleBean实例。

\n\n

这种行为的原因可以解释如下:

\n\n

如果使用 @Configuration,所有标记为 @Bean 的方法都将被包装到 …

java singleton javabeans spring-boot

7
推荐指数
0
解决办法
5165
查看次数

将依赖注入与单例设计模式混合

我的项目中有一个单例,如下所示:

//Create a Singleton
static MySingleton Instance;
private static readonly object Padlock = new object();
/// <summary>
/// Singelton Method, to make sure only one instance of this class exists at runtime.
/// </summary>
/// <returns></returns>
public static MySingleton GetInstance()
{
  //Thread Safety
  lock (Padlock)
  {
    if (Instance == null)
    {
      Instance = new MySingleton();
    }
    return Instance;
  }
}

private MySingleton()
{
}

//[...]
Run Code Online (Sandbox Code Playgroud)

Singleton 包含几个其他类作为 Properties,它们永远不应该为 null。

通常我会使用DependencyInjection来保证每个新对象在实例化时获得所有必要的参数。像这样:

IHelperClass Helper {get; set;}

IExectiveClass Executive {get; set;} …
Run Code Online (Sandbox Code Playgroud)

c# singleton dependency-injection

7
推荐指数
1
解决办法
4004
查看次数

符合 ObservableObject 的 SwiftUI 类应该是 Singleton?

我被认为是 SwiftUI 的新手,我有下面的 ViewModel。但我不确定 MyViewModel 应该是单例的。这样的用法正确吗?符合 ObservableObject 的最佳实践/用法是什么?

class MyViewModel: ObservableObject {
    static let shared: MyViewModel = MyViewModel()
    
    @Published var result: String = ""
    
    private init() { }
    
    // some functions
}

struct ContentView: View {
    @ObservedObject private var vm = MyViewModel.shared
    
    var body: some View {
        Text(vm.result)
    }
}
Run Code Online (Sandbox Code Playgroud)

singleton swift swiftui observableobject

7
推荐指数
1
解决办法
4317
查看次数

如何在 dart 中实现具有异步初始化和 null 安全性的单例?

我需要一个用于共享首选项的单例,它具有异步初始化,但也适用于空安全。通常我使用以下单例实现,但是拥有空安全性的单例的最佳方法是什么?

class SharedPrefs {
static SharedPrefs _instance;
static Future<Null> _mutex;

static Future<SharedPrefs> getInstance() async {
  if (_mutex != null) {
    await _mutex;
  }
  var completer = Completer<Null>();
  _mutex = completer.future;

  if (_instance == null) {
    _instance = SharedPrefs();
    await _instance.init();
  }

  completer.complete();
  _mutex = null;

  return _instance;
}

SharedPreferences prefs;

SharedPrefs();

Future<SharedPrefs> init() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  return this;
}

dynamic get(String key) {
  return prefs.getString(key);
}

Future<bool> put(String key, dynamic value) async {
  return await prefs.setString(key,value); …
Run Code Online (Sandbox Code Playgroud)

singleton asynchronous dart flutter dart-null-safety

7
推荐指数
1
解决办法
5253
查看次数