该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生活在哪里,它的目的是什么?
我正在研究一个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) 我有这个单身模式,它运行正常.但是当我用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)
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)
它没有关系,但在初始化时,我从文件中读取了一堆单词,然后将它们保存在地图实例中.
谢谢
我们假设我们有这个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/中修复
我意识到我应该只有一个被称为一次StdSchedulerFactory运行的对象实例.到目前为止,我实例化了这样的对象
StdSchedulerFactory sf = new StdSchedulerFactory(properties);
Run Code Online (Sandbox Code Playgroud)
而属性是一个NameValueCollection.如何为此对象编写Singleton类,以便变量sf在整个程序中始终具有一个实例?
我在试图弄清楚如何做到这一点时遇到了一些麻烦(如果可能的话).
我有一个使用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) 我正在做我的日常工作,我意识到尽管我经常使用@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}\nRun 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}\nRun Code Online (Sandbox Code Playgroud)\n\n第一段代码工作正常,并且正如预期的那样,SimpleBeanConsumer 将获得指向单例 SimpleBean 的链接。但不幸的是,它不能在签名环境中工作。
\n\n第二种配置是完全不正确的,因为spring会创建一个SimpleBean的单例bean,但是SimpleBeanConsumer会获得另一个不受spring上下文控制的SimpleBean实例。
\n\n这种行为的原因可以解释如下:
\n\n如果使用 @Configuration,所有标记为 @Bean 的方法都将被包装到 …
我的项目中有一个单例,如下所示:
//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) 我被认为是 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) 我需要一个用于共享首选项的单例,它具有异步初始化,但也适用于空安全。通常我使用以下单例实现,但是拥有空安全性的单例的最佳方法是什么?
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)