Possible开发者_如何学JAVA Duplicate:
What is a singleton in C#?
could some body please explain me singleton pattern? in c# please and what is it use for
A singleton is a class that only allows one instance of itself to be created.
An example of a singleton in C#.
public class Singleton
{
private static Singleton _default;
public static Singleton Default
{
get
{
if (_default == null)
_default = new Singleton();
return _default;
}
}
private Singleton()
{ }
public void SomeMethod()
{
// Do something...
}
}
Then you would access it like:
Singleton.Default.SomeMethod();
http://en.wikipedia.org/wiki/Singleton_pattern
A singleton pattern is a class that only ever allows one instance of itself to be created. If someone tries to create another instance, they just get a reference to the first one.
It's much derided due to people's tendencies to treat it as a God object where they just dump all sorts of stuff, and also because it can complicate unit testing. But it has its place if you know what you're doing, just like goto
and multiple return points from functions :-)
public class SingleTonSample
{
private static SingleTonSample instance;
public static SingleTonSample Instance
{
get
{
return instance?? new SingleTonSample();
}
}
private SingleTonSample()
{
/// todo
}
public void Foo()
{
///todo
}
}
public class UseSingleton
{
public void Test()
{
SingleTonSample sample = SingleTonSample.Instance;
sample.Foo();
}
}
精彩评论