C# 中的Singleton模式

时间:2022-09-02 08:38:41

一般写Singleton基本都是一下这个套路

class Singleton 
{
public static Singleton instance;

private Singleton()
{

}

public static Singleton Getinstance()
{
if(instatnce == null)
{
instance = new Singleton();
}

return instance;
}
}

但是今天学到一个C#独有的Singleton写法:

class sealed Singleton 
{
public static readonly Singleton instance = new Singleton();

private Singleton()
{

}
}

这种写法简单实用,大大减少了代码量。

但是缺点就是无法被继承,并且启动时就被初始化,无法延迟初始化。

 

我以这种写法,写了一个简单的LoadBalance类。

public sealed class LoadBalancer
{
public static readonly LoadBalancer balancer = new LoadBalancer();
private ArrayList servers = new ArrayList();
private Random random = new Random();

protected LoadBalancer()
{
servers.Add("SERVER I");
servers.Add("SERVER II");
servers.Add("SERVER III");
servers.Add("SERVER IV");
servers.Add("SERVER V");
}

public string Server
{
get
{
int i = random.Next(servers.Count);
return servers[i].ToString();
}
}
}

class Program
{
static void Main(string[] args)
{
LoadBalancer b1 = LoadBalancer.balancer;
LoadBalancer b2 = LoadBalancer.balancer;
LoadBalancer b3 = LoadBalancer.balancer;
LoadBalancer b4 = LoadBalancer.balancer;

if (b1 == b2 || b2 == b3 || b3 == b4)
Console.WriteLine("Same instance");
Console.WriteLine(b1.Server);
Console.WriteLine(b2.Server);
Console.WriteLine(b3.Server);
Console.WriteLine(b4.Server);

Console.ReadLine();
}
}

调用的结果是:

 

Same instance

SERVER III

SERVER I

SERVER IV

SERVER IV