如何在 C# 中实现单例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/246710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement a singleton in C#?
提问by Andre
How do I implement the singleton pattern in C#? I want to put my constants and some basic functions in it as I use those everywhere in my project. I want to have them 'Global' and not need to manually bind them every object I create.
如何在 C# 中实现单例模式?我想把我的常量和一些基本函数放在里面,因为我在我的项目中到处都使用它们。我想让它们“全局”,而不需要手动将它们绑定到我创建的每个对象。
采纳答案by tvanfosson
If you are just storing some global values and have some methods that don't need state, you don't need singleton. Just make the class and its properties/methods static.
如果您只是存储一些全局值并且有一些不需要状态的方法,则不需要单例。只需将类及其属性/方法设为静态即可。
public static class GlobalSomething
{
public static int NumberOfSomething { get; set; }
public static string MangleString( string someValue )
{
}
}
Singleton is most useful when you have a normal class with state, but you only want one of them. The links that others have provided should be useful in exploring the Singleton pattern.
当你有一个带状态的普通类,但你只想要其中一个时,单例是最有用的。其他人提供的链接应该有助于探索单例模式。
回答by cciotti
I would recommend you read the article Exploring the Singleton Design Patternavailable on MSDN. It details the features of the framework which make the pattern simple to implement.
我建议您阅读MSDN 上提供的探索单例设计模式一文。它详细介绍了框架的特性,这些特性使模式易于实现。
As an aside, I'd check out the related reading on SO regarding Singletons.
顺便说一句,我会查看关于 SO 关于 Singletons的相关阅读。
回答by yfeldblum
Singleton != Global
. You seem to be looking for the keyword static
.
Singleton != Global
. 您似乎在寻找关键字static
。
回答by tvanfosson
Singletons only make sense if bothof these conditions are true:
只有当这两个条件都为真时,单身才有意义:
- The object must be global
- There must only ever exist a singleinstance of the object
- 对象必须是全局的
- 必须只存在对象的单个实例
Note that #2 does not mean that you'd likethe object to only have a single instance - if thats the case, simply instantiate it only once - it means that there must(as in, it's dangerous for this not to be true) only ever be a single instance.
请注意,#2,并不意味着你会喜欢的对象只有一个实例-如果多数民众赞成的情况下,简单地初始化它只有一次-这意味着必须(如中,这是危险的,这是不正确的)永远只是一个实例。
If you want global, just make a global instance of some (non signleton) object (or make it static or whatever). If you want only one instance, again, static is your friend. Also, simply instantiate only one object.
如果您想要全局,只需创建某个(非signleton)对象的全局实例(或使其成为静态或其他)。如果你只想要一个实例,静态是你的朋友。此外,只需实例化一个对象。
Thats my opinion anyway.
反正这就是我的意见。
回答by Sam Meldrum
Ignoring the issue of whether or not you should be using the Singleton pattern, which has been discussed elsewhere, I would implement a singleton like this:
忽略是否应该使用已在别处讨论过的单例模式的问题,我将实现这样的单例:
/// <summary>
/// Thread-safe singleton implementation
/// </summary>
public sealed class MySingleton {
private static volatile MySingleton instance = null;
private static object syncRoot = new object();
/// <summary>
/// The instance of the singleton
/// safe for multithreading
/// </summary>
public static MySingleton Instance {
get {
// only create a new instance if one doesn't already exist.
if (instance == null) {
// use this lock to ensure that only one thread can access
// this block of code at once.
lock (syncRoot) {
if (instance == null) {
instance = new MySingleton();
}
}
}
// return instance where it was just created or already existed.
return instance;
}
}
/// <summary>
/// This constructor must be kept private
/// only access the singleton through the static Instance property
/// </summary>
private MySingleton() {
}
}
回答by user7375
Static singleton is pretty much an anti pattern if you want a loosely coupled design. Avoid if possible, and unless this is a very simple system I would recommend having a look at one of the many dependency injection frameworks available, such as http://ninject.org/or http://code.google.com/p/autofac/.
如果您想要松散耦合的设计,静态单例几乎是一种反模式。尽可能避免,除非这是一个非常简单的系统,否则我建议您查看许多可用的依赖注入框架之一,例如http://ninject.org/或http://code.google.com/p /autofac/。
To register / consume a type configured as a singleton in autofac you would do something like the following:
要在 autofac 中注册/使用配置为单例的类型,您可以执行以下操作:
var builder = new ContainerBuilder()
builder.Register(typeof(Dependency)).SingletonScoped()
builder.Register(c => new RequiresDependency(c.Resolve<Dependency>()))
var container = builder.Build();
var configured = container.Resolve<RequiresDependency>();
The accepted answer is a terrible solution by the way, at least check the chaps who actually implemented the pattern.
顺便说一句,接受的答案是一个糟糕的解决方案,至少检查一下实际实施该模式的人。
回答by FlySwat
You can really simplify a singleton implementation, this is what I use:
您可以真正简化单例实现,这就是我使用的:
internal FooService() { }
static FooService() { }
private static readonly FooService _instance = new FooService();
public static FooService Instance
{
get { return _instance; }
}
回答by munificent
What you are describing is merely static functions and constants, nota singleton. The singleton design pattern (which is very rarely needed) describes a class that isinstantiated, but only once, automatically, when first used.
您所描述的只是静态函数和常量,而不是单例。单例设计模式(很少需要)描述了一个被实例化的类,但只有在第一次使用时自动实例化一次。
It combines lazy initialization with a check to prevent multiple instantiation. It's only really useful for classes that wrap some concept that is physically singular, such as a wrapper around a hardware device.
它结合了延迟初始化和检查以防止多次实例化。它只对包装一些物理上单一的概念的类真正有用,例如围绕硬件设备的包装器。
Static constants and functions are just that: code that doesn't need an instance at all.
静态常量和函数就是:根本不需要实例的代码。
Ask yourself this: "Will this class break if there is more than one instance of it?" If the answer is no, you don't need a singleton.
问问自己:“如果有多个实例,这个类会中断吗?” 如果答案是否定的,则您不需要单身人士。
回答by Newtopian
hmmm... Few constants with related functions... would that not better be achieved through enums ? I know you can create a custom enum in Java with methods and all, the same should be attainable in C#, if not directly supported then can be done with simple class singleton with private constructor.
嗯...很少有具有相关功能的常量...通过枚举不是更好地实现吗?我知道您可以使用方法和所有方法在 Java 中创建自定义枚举,在 C# 中应该可以实现相同的功能,如果不直接支持,则可以使用带有私有构造函数的简单类单例来完成。
If your constants are semantically related you should considered enums (or equivalent concept) you will gain all advantages of the const static variables + you will be able to use to your advantage the type checking of the compiler.
如果您的常量在语义上相关,您应该考虑枚举(或等效概念),您将获得 const 静态变量的所有优点+您将能够利用编译器的类型检查。
My 2 cent
我的 2 美分
回答by Charles Bretana
By hiding public constructor, adding a private static field to hold this only instance, and adding a static factory method (with lazy initializer) to return that single instance
通过隐藏公共构造函数,添加一个私有静态字段来保存这个唯一的实例,并添加一个静态工厂方法(带有惰性初始化程序)来返回该单个实例
public class MySingleton
{
private static MySingleton sngltn;
private static object locker;
private MySingleton() {} // Hides parameterless ctor, inhibits use of new()
public static MySingleton GetMySingleton()
{
lock(locker)
return sngltn?? new MySingleton();
}
}