C#中的单例是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2155688/
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
What is a singleton in C#?
提问by Sergio Tapia
What is a Singleton and when should I use it?
什么是单例,我应该什么时候使用它?
采纳答案by Daniel May
A singleton is a class which only allows one instance of itself to be created - and gives simple, easy access to said instance. The singleton premise is a pattern across software development.
单例是一个类,它只允许创建自己的一个实例 - 并提供对所述实例的简单、轻松的访问。单例前提是跨软件开发的一种模式。
There is a C# implementation "Implementing the Singleton Pattern in C#"covering most of what you need to know - including some good advice regarding thread safety.
有一个 C# 实现“在 C# 中实现单例模式”,涵盖了您需要了解的大部分内容 - 包括一些关于线程安全的好建议。
To be honest, It's very rare that you need to implement a singleton - in my opinion it should be one of those things you should be aware of, even if it's not used too often.
老实说,您很少需要实现单例 - 在我看来,它应该是您应该注意的事情之一,即使它不经常使用。
回答by Aaronaught
What it is:A class for which there is just one, persistent instance across the lifetime of an application. See Singleton Pattern.
它是什么:一个在应用程序的整个生命周期中只有一个持久实例的类。请参阅单例模式。
When you should use it:As little as possible. Only when you are absolutely certainthat you need it. I'm reluctant to say "never", but there is usually a better alternative, such as Dependency Injection or simply a static class.
什么时候应该使用它:尽可能少。只有当您绝对确定您需要它时。我不愿意说“从不”,但通常有更好的选择,例如依赖注入或简单的静态类。
回答by radex
Here's what singleton is: http://en.wikipedia.org/wiki/Singleton_pattern
这是单身人士:http: //en.wikipedia.org/wiki/Singleton_pattern
I don't know C#, but it's actually the same thing in all languages, only implementation differs.
我不知道 C#,但它实际上在所有语言中都是一样的,只是实现不同。
You should generally avoid singleton when it's possible, but in some situations it's very convenient.
您通常应该尽可能避免使用单例,但在某些情况下它非常方便。
Sorry for my English ;)
对不起我的英语不好 ;)
回答by marcgg
It's a design pattern and it's not specific to c#. More about it all over the internet and SO, like on this wikipedia article.
这是一种设计模式,并非特定于 c#。在互联网和 SO 上有更多关于它的信息,就像这篇维基百科文章一样。
In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects (say, five). Some consider it an anti-pattern, judging that it is overused, introduces unnecessary limitations in situations where a sole instance of a class is not actually required, and introduces global state into an application.
在软件工程中,单例模式是一种设计模式,用于将类的实例化限制为一个对象。当只需要一个对象来协调整个系统的操作时,这很有用。这个概念有时被推广到当只有一个对象存在时更有效地运行的系统,或者将实例化限制为一定数量的对象(例如,五个)。有些人认为它是一种反模式,认为它被过度使用,在实际上不需要类的唯一实例的情况下引入了不必要的限制,并将全局状态引入到应用程序中。
You should use it if you want a class that can only be instanciated once.
如果你想要一个只能实例化一次的类,你应该使用它。
回答by BFree
A Singleton (and this isn't tied to C#, it's an OO design pattern) is when you want to allow only ONE instance of a class to be created throughout your application. Useages would typically include global resources, although I will say from personal experience, they're very often the source of great pain.
单例(这与 C# 无关,它是一种 OO 设计模式)是指您希望在整个应用程序中只创建一个类的实例。用途通常包括全球资源,尽管我会根据个人经验说,它们通常是巨大痛苦的根源。
回答by TabbyCool
Whilst the there can only ever be one instance of a singleton, it is not the same as a static class. A static class can only contain static methods and can never be instantiated, whereas the instance of a singleton may be used in the same way as any other object.
虽然单例只能有一个实例,但它与静态类不同。静态类只能包含静态方法并且永远不能被实例化,而单例的实例可以像任何其他对象一样使用。
回答by Chris Simmons
You asked for C#. Trivial example:
你要求 C#。简单的例子:
public class Singleton
{
private Singleton()
{
// Prevent outside instantiation
}
private static readonly Singleton _singleton = new Singleton();
public static Singleton GetSingleton()
{
return _singleton;
}
}
回答by Marnix v. R.
another way to implement singleton in c#, i personally prefer this way because you can access the instance of the singeton class as a property instead of a method.
在 c# 中实现单例的另一种方法,我个人更喜欢这种方式,因为您可以将单例类的实例作为属性而不是方法来访问。
public class Singleton
{
private static Singleton instance;
private Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null)
instance = new Singleton();
return instance;
}
}
//instance methods
}
but well, as far as i know both ways are considered 'right' so it's just a thing of personal flavor.
但是,据我所知,这两种方式都被认为是“正确的”,所以这只是个人风格的事情。
回答by brykneval
using System;
using System.Collections.Generic;
class MainApp
{
static void Main()
{
LoadBalancer oldbalancer = null;
for (int i = 0; i < 15; i++)
{
LoadBalancer balancerNew = LoadBalancer.GetLoadBalancer();
if (oldbalancer == balancerNew && oldbalancer != null)
{
Console.WriteLine("{0} SameInstance {1}", oldbalancer.Server, balancerNew.Server);
}
oldbalancer = balancerNew;
}
Console.ReadKey();
}
}
class LoadBalancer
{
private static LoadBalancer _instance;
private List<string> _servers = new List<string>();
private Random _random = new Random();
private static object syncLock = new object();
private LoadBalancer()
{
_servers.Add("ServerI");
_servers.Add("ServerII");
_servers.Add("ServerIII");
_servers.Add("ServerIV");
_servers.Add("ServerV");
}
public static LoadBalancer GetLoadBalancer()
{
if (_instance == null)
{
lock (syncLock)
{
if (_instance == null)
{
_instance = new LoadBalancer();
}
}
}
return _instance;
}
public string Server
{
get
{
int r = _random.Next(_servers.Count);
return _servers[r].ToString();
}
}
}
I took code from dofactory.com, nothing so fancy but I find this far good than examples with Foo and Baradditionally book from Judith Bishop on C# 3.0 Design Patterns has example about active application in mac dock.
我从dofactory.com 获取了代码,没什么特别的,但我发现这比 Foo 和 Bar 的示例还好,另外还有 Judith Bishop 关于 C# 3.0 设计模式的书,有关于 mac Dock 中活动应用程序的示例。
If you look at code we are actually building new objects on forloop, so that creates new object but reuses instance as a result of which the oldbalancer and newbalancer has same instance, How? its due to statickeyword used on function GetLoadBalancer(), despite of having different server value which is random list, static on GetLoadBalancer()belongs to the type itself rather than to a specific object.
如果您查看代码,我们实际上是在for循环上构建新对象,这样会创建新对象但重用实例,结果 oldbalancer 和 newbalancer 具有相同的实例,如何?这是由于函数GetLoadBalancer()上使用的static关键字,尽管具有不同的服务器值,即随机列表,但GetLoadBalancer()上的static属于类型本身而不是特定对象。
Additionally there is double check lockinghere
此外,还有双重检查锁定在这里
if (_instance == null)
{
lock (syncLock)
{
if (_instance == null)
since from MSDN
从 MSDN 开始
The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.
lock 关键字确保一个线程不会进入代码的临界区,而另一个线程处于临界区。如果另一个线程试图输入一个锁定的代码,它将等待、阻塞,直到对象被释放。
so every-time mutual-exclusion lock is issued, even if it don't need to which is unnecessary so we have null check.
所以每次都发出互斥锁,即使它不需要,这是不必要的,所以我们有空检查。
Hopefully it helps in clearing more.
希望它有助于清除更多。
And please comment if I my understanding is directing wrong ways.
如果我的理解指向错误的方式,请发表评论。
回答by Manish Jain
I use it for lookup data. Load once from DB.
我用它来查找数据。从数据库加载一次。
public sealed class APILookup
{
private static readonly APILookup _instance = new APILookup();
private Dictionary<string, int> _lookup;
private APILookup()
{
try
{
_lookup = Utility.GetLookup();
}
catch { }
}
static APILookup()
{
}
public static APILookup Instance
{
get
{
return _instance;
}
}
public Dictionary<string, int> GetLookup()
{
return _lookup;
}
}